ASP.NET Hosting

Forcing event unsubscription

Given my own experience, I'd say that events are the main source of leaks in .NET. They deserve double- and even triple-checks. Each time you add a subscription to an event in your code, most likely with +=, you should worry about the consequences and ask yourself whether you need to add a -= somewhere to unsubscribe from the event. If you have to, do it immediately before you forget about it. Often, you'll do that in a Dispose method.

Don't forget that subject objects keep the observer (or listener, or subscriber) objects that observe them alive. See this post of mine if you need a refresher about the subject.

Having listener objects unsubscribe from the events they subscribe to is usually the recommended way to ensure they can be collected. However, when you absolutely know that a subject object wont publish notifications anymore and you wish that its subscribers can be released, you can force the removal of all the subscriptions to the subject object. Here is how this can be achieved:

if (SomeEvent != null)
  foreach (EventHandler handler in SomeEvent.GetInvocationList())
    SomeEvent -= handler;

Update: As suggested by Steve in a comment, SomeEvent = null is enough!
Update: I've improved the sample source code to show if the listeners are dead or alive.
Update: See also this new article of mine.

I have a code sample available for you to download.


Comments have been disabled for this content.