V3084. Anonymous function is used to unsubscribe from event. No handlers will be unsubscribed, as a separate delegate instance is created for each anonymous function declaration.


The analyzer detected a possible error that has to do with using anonymous functions to unsubscribe from an event. Consider the following example:

public event EventHandler MyEvent;
void Subscribe()
{
    MyEvent += (sender, e) => HandleMyEvent(e);
}

void UnSubscribe()
{
    MyEvent -= (sender, e) => HandleMyEvent(e);
}

In this example, methods 'Subscribe' and 'UnSubscribe' are declared respectively for subscribing to and unsubscribing from the 'MyEvent' event. A lambda expression is used as an event handler. Subscription to the event will be successfully fulfilled in the 'Subscribe' method, and the handler (the anonymous function) will be added to the event.

However, the 'UnSubscribe' method will fail to unsubscribe the handler previously subscribed in the 'Subscribe' method. After executing this method, the 'MyEvent' event will still be containing the handler added in 'Subscribe'.

This behavior is explained by the fact that every declaration of an anonymous function results in creating a separate delegate instance – of type EventHandler in our case. So, what is subscribed in the 'Subscribe' method is 'delegate 1' while 'delegate 2' gets unsubscribed in the 'Unsubscribe' method, despite these two delegates having identical bodies. Since our event contains only 'delegate 1' by the time the handler is unsubscribed, unsubscribing from 'delegate 2' will not affect the value of 'MyEvent'.

To correctly subscribe to events using anonymous functions (when subsequent unsubscription is required), you can keep the lambda handler in a separate variable, using it both to subscribe to and unsubscribe from an event:

public event EventHandler MyEvent;
EventHandler _handler;
void Subscribe()
{
    _handler = (sender, e) => HandleMyEvent(sender, e);
    MyEvent += _handler;
}

void UnSubscribe()
{
    MyEvent -= _handler;
}

Bugs Found

Checked Projects
346
Collected Errors
13 188