Home >Backend Development >C++ >How to Unsubscribe from Lambda Event Handlers in C#?

How to Unsubscribe from Lambda Event Handlers in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-20 09:46:09743browse

How to Unsubscribe from Lambda Event Handlers in C#?

Remove Lambda event handler in C#

In C#, Lambda expressions provide a concise way to define simple event handlers. For example, subscribing to a click event using a Lambda expression is very simple:

<code class="language-csharp">button.Click += (s, e) => MessageBox.Show("Woho");</code>

But how do I subsequently unsubscribe from this event?

Use delegate to unsubscribe

The C# specification states that Lambda expressions and anonymous delegates do not always generate the same delegate. Therefore, to ensure reliable unsubscription, you can explicitly track the delegate instance used:

<code class="language-csharp">EventHandler handler = (s, e) => MessageBox.Show("Woho");

button.Click += handler;
...
button.Click -= handler;</code>

Use independent methods

If you don't want to use a delegate, you can define a separate method for the event handler:

<code class="language-csharp">public void ShowWoho(object sender, EventArgs e)
{
     MessageBox.Show("Woho");
}

...

button.Click += ShowWoho;
...
button.Click -= ShowWoho;</code>

Self-removing Lambda handler

If you wish to use a Lambda expression to create a self-removing event handler, you can reference the delegate in the Lambda expression. However, you must first assign the variable to null:

<code class="language-csharp">EventHandler handler = null;
handler = (sender, args) =>
{
    button.Click -= handler; // 取消订阅
    // 在此处添加您的单次执行代码
};
button.Click += handler;</code>

Use delegate class for encapsulation

It is possible to encapsulate self-removal functionality into a delegate class, but this may be more complicated due to the abstract nature of the event:

<code class="language-csharp">button.Click += Delegates.AutoUnsubscribe<EventHandler>((sender, args) =>
{
    // 此处的单次执行代码
}, handler => button.Click -= handler);</code>

The above is the detailed content of How to Unsubscribe from Lambda Event Handlers in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn