Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would the following pattern of unsubscribing your self from an event via closure cause any problems?

Consider the situation in which you want to subscribe to an event for one and only one notification. Once the first notification lands, you unsubscribe from all future events. Would the following pattern present any memory issues? It works, but I wasn't sure if the self-referencing closure could keeps things around in memory longer than desired.

public class Entity
{
    public event EventHandler NotifyEvent;
}

// And then, elsewhere, for a listen-once handler, we might do this:
Entity entity = new Entity();
Action<object, EventArgs> listener = null;
listener = (sender, args) =>
{
    // do something interesting
    // unsubscribe, so we only get 1 event notification
    entity.NotifyEvent -= new EventHandler(listener);
};
entity.NotifyEvent += new EventHandler(listener);

Note that you have to declare 'listener' and assign a value (null). Otherwise the compiler complains about 'Use of unassigned local variable listener'

like image 702
Matt Avatar asked Nov 03 '11 16:11

Matt


People also ask

Is it possible to unsubscribe from events?

You cannot easily unsubscribe from an event if you used an anonymous function to subscribe to it. To unsubscribe in this scenario, go back to the code where you subscribe to the event, store the anonymous function in a delegate variable, and then add the delegate to the event.

What are events in C# with example?

Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts.

Can events be static C#?

An event may be declared as a static event by using the static keyword. This makes the event available to callers at any time, even if no instance of the class exists. For more information, see Static Classes and Static Class Members. An event can be marked as a virtual event by using the virtual keyword.


1 Answers

There is nothing wrong with this pattern. It's the very same pattern I and many others use for assigning and removing a lambda expression to an event handler.

like image 113
JaredPar Avatar answered Oct 03 '22 08:10

JaredPar