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 question is: how to remove or unsubscribe from these event handlers.
The C# specification does not guarantee that two Lambda expressions with the same code will produce equal delegates. To ensure successful unsubscription, it is recommended to store the delegate instance explicitly.
Use named EventHandler methods
The most straightforward way is to define a method and assign it as an event handler:
<code class="language-csharp">public void ShowWoho(object sender, EventArgs e) { MessageBox.Show("Woho"); } ... button.Click += ShowWoho; ... button.Click -= ShowWoho;</code>
Use delegates to store variables
To create a self-removing event handler using a Lambda expression, you can use a delegate to store the variable:
<code class="language-csharp">EventHandler handler = null; handler = (sender, args) => { button.Click -= handler; // 取消订阅 // 在此处添加仅执行一次的代码 }; button.Click += handler;</code>
Use helper methods
While helper methods cannot be used to encapsulate event handlers due to limitations in event representation, generic delegates can provide a solution:
<code class="language-csharp">button.Click += Delegates.AutoUnsubscribe<EventHandler>( (sender, args) => { // 此处添加仅执行一次的代码 }, handler => button.Click -= handler);</code>
By following these methods, developers can effectively remove Lambda event handlers, ensuring proper event management and control over the event subscription lifecycle.
The above is the detailed content of How to Unsubscribe Lambda Event Handlers in C#?. For more information, please follow other related articles on the PHP Chinese website!