Method to unsubscribe from Lambda event handler in C#
]In C#, anonymous Lambda expressions provide a convenient way to create event handlers. However, a common problem is: how to remove or unsubscribe to these event handlers.
The C# specification does not guarantee that two codes have the same Lambda expressions that produce equal delegates. To ensure successful unsubscribe, it is recommended to explicitly store delegated instances.
Use the named EventHandler method
]The most direct way is to define a method and assign it as an event handler:
public void ShowWoho(object sender, EventArgs e)
{
MessageBox.Show("Woho");
}
...
button.Click = ShowWoho;
...
button.Click -= ShowWoho;
Storing variables using delegate
]To create a self-removed event handler using a Lambda expression, you can use the delegate storage variable:
EventHandler handler = null;
handler = (sender, args) =>
{
button.Click -= handler; // 取消订阅
// 在此处添加仅执行一次的代码
};
button.Click = handler;
Use helper method
Although helper methods cannot be used to encapsulate event handlers due to event representation limitations, generic delegates can provide solutions:
button.Click = Delegates.AutoUnsubscribe(
(sender, args) =>
{
// 此处添加仅执行一次的代码
},
handler => button.Click -= handler);
By following these methods, developers can effectively remove Lambda event handlers, ensuring proper event management and control over the event subscription lifecycle.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3