Should I unsubscribe from events? [duplicate]

Well, let’s take the last question first. You can’t reliably unsubscribe from an event that you’ve subscribed to directly with a lambda expression. You either need to keep a variable around with the delegate in (so you can still use a lambda expression) or you need to use a method group conversion instead.

Now as for whether you actually need to unsubscribe, it depends on the relationship between the event producer and the event consumer. If the event producer should live for longer than the event consumer, you should unsubscribe – because otherwise the producer will have a reference to the consumer, keeping it alive for longer than it should be. The event handler will also keep getting called for as long as the producer produces it.

Now in many cases that’s not a problem – for example, in a form the button that raises the Click event is likely to live for about as long as the form on which it’s created, where the handler is typically subscribed… so there’s no need to unsubscribe. This is very typical for a GUI.

Likewise if you create a WebClient solely for the purpose of a single asynchronous request, subscribe to the relevant event and start the asynchronous request, then the WebClient itself will be eligible for garbage collection when the request has finished (assuming you don’t keep a reference elsewhere).

Basically, you should always consider the relationship between the producer and the consumer. If the producer is going to live longer than you want the consumer to, or it’s going to continue raising the event after you’re no longer interested in it, then you should unsubscribe.

Leave a Comment

tech