Fabrice's weblog

Tools and Source


My .NET Toolbox
An error occured. See the script errors signaled by your web browser.
No tools selected yet
.NET tools by SharpToolbox.com

Read sample chapters or buy LINQ in Action now!
Our LINQ book is also available on AMAZON

.NET jobs

Emplois .NET


ASP.NET Hosting transatlantys




Selected content


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.


Steve said:

Isn't SomeEvent = null; enough?

# September 9, 2009 7:02 AM

Fabrice Marguerie said:

You're right Steve, this works fine. Thanks!

# September 9, 2009 8:30 AM

Mark Sowul said:

"Don't forget that observer (or listener, or subscriber) objects keep the subjects they observe alive."

This is backwards.  The subject keeps the observers alive (as your own diagram indicates).  For that reason, setting an object's event to null does nothing to allow the object itself to get collected.  The event producer is not kept alive by its subscribers.

# September 9, 2009 2:09 PM

Jigar said:

How to set shared events to null (in case of vb.net) in .Net 2.0?

# November 3, 2009 1:59 AM

Fabrice Marguerie said:

VB is hiding things so much, that I don't know if it's possible. I don't see how.

# November 4, 2009 5:34 PM

dxq said:

Some object's Event only can read,can not to assign null.It shows error "XXXX can only appear on the left hand side of += or -="

# January 13, 2010 10:53 AM