(2003 to 2005)

Why is the 'Observer' a 'Participant' in a garbage collected environment?

Thu Jan 15 00:21:00 UTC+1100 2004


The 'Event pattern' is a 'first class' concept in the .NET framework.

There is language level support for this pattern in C# with keywords such as 'event', 'add', 'remove', etc. The Event pattern is implemented using MulticastDelegates.

The Event pattern is similar to the Observer pattern. The Observer pattern (as explained by the Gang of Four) had its implementation characteristics specified assuming an environment that supported deterministic finalization. The 4th note on implementation of the Observer is:

4. Dangling references to deleted subjects. Deleting a subject should not produce dangling references in its observers. One way to avoid dangling references is to make the subject notify its observers as it is deleted so that they can reset their reference to it. In general, simply deleting the observers is not an option, because other objects may reference them, or they may be observing other subjects as well.

As you can see, this assumes that some part of your code is responsible for the lifetime management of the observers. In a garbage collected environment like .NET generally lifetime management like this is not required. No part of your code needs to explicitly take responsibility for the lifetime of an object. The exception is when an object implements the IDisposable interface.. but not all objects do.

I could go on, and one day I will, but for now I want to say that in .NET either the Event pattern is broken or garbage collection is a myth.


Copyright © 2003-2005 John Elliot