Click here to Skip to main content
15,881,709 members
Articles / Programming Languages / C#

The .NET Weak Event Pattern in C#

Rate me:
Please Sign up or sign in to vote.
4.63/5 (38 votes)
3 Mar 2014CPOL8 min read 94K   114   69   16
The .NET weak event pattern in C#

Introduction

As you may know, event handlers are a common source of memory leaks caused by the persistence of objects that are not used anymore, and you may think should have been collected, but are not, and for good reason.

In this (hopefully) short article, I’ll present the issue with event handlers in the context of the .NET Framework, then I’ll show you how you can implement the standard solution to this issue, the weak event pattern, in two ways, either using:

  • the “legacy” (well, before .NET 4.5, so not that old) approach which is quite cumbersome to implement
  • the new approach provided by the .NET 4.5 framework which is as simple as it can be

(The source code is available here.)

The Common Stuff

Before diving into the core of the article, let’s review two items which are used extensively in the code: a class and a method.

The Event-Source

Let me present you a basic but useful event-source class which exposes just enough complexity to illustrate the point:

C#
public class EventSource
{
    public event EventHandler<EventArgs> Event = delegate { };

    public void Raise()
    {
        Event(this, EventArgs.Empty);
    }
}

For those who wonder what the strange empty delegate initialization is: it’s a trick to be sure the event is always initialized, without having to check each time if it’s non-null before using it.

The GC Triggering Utility Method

In .NET, the garbage collection is triggered in a non-deterministic manner, which is not good for our tests that need to track the state of objects in a deterministic manner.

So we’ll regularly have to trigger ourselves a GC, and to avoid duplicating plumbing code, it’s been factorized in a dedicated method:

C#
static void TriggerGC()
{
    Console.WriteLine("Starting GC.");

    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();

    Console.WriteLine("GC finished.");
}

Not rocket science, but it deserves a little explanation if you’re not familiar with this pattern:

  • First GC.Collect() triggers the .NET CLR garbage-collector which will take care of sweeping unused objects, and for objects whose class has no finalizer (a.k.a. destructor in C#), it’s enough
  • GC.WaitForPendingFinalizers() waits for the finalizers of other objects to execute; we need it because as you’ll see, we’ll use the finalizer methods to know when our objects are collected
  • Second GC.Collect() ensures the newly finalized objects are swept too.

The Issue

So first things first, let’s try to understand what the problem is with event listeners, with the help of some theory and, most importantly, a demo.

Background

When an object acting as an event listener registers one of its instance methods as an event handler on an object that produces events (the event source), the event source must keep a reference to the event listener object in order to raise the event in the context of this listener.

This is fair enough, but if this reference is a strong reference, then the listener acts as a dependency of the event source and can’t be garbage-collected even if the last object referencing it is the event source.

Here is a detailed diagram of what happens under the hood:

Events handlers issue

Events handlers issue

This is not an issue if you can control the life time of the listener object as you can unsubscribe from the event source when you don’t need the listener anymore, typically using the disposable pattern.
But if you can’t identify a single point of responsibility for the life time of the listener, then you can’t dispose of it in a deterministic manner and you have to rely on the garbage collection process … which will never consider your object as ready for collection as long as the event source is alive!

Demo

Theory is all good but let’s see the issue with real code.

Here is our brave event listener, just a bit naive, and we’ll quickly understand why:

C#
public class NaiveEventListener
{
    private void OnEvent(object source, EventArgs args)
    {
        Console.WriteLine("EventListener received event.");
    }

    public NaiveEventListener(EventSource source)
    {
        source.Event += OnEvent;
    }

    ~NaiveEventListener()
    {
        Console.WriteLine("NaiveEventListener finalized.");
    }
}

Let’s see how this implementation behaves with a simple use-case:

C#
Console.WriteLine("=== Naive listener (bad) ===");

EventSource source = new EventSource();

NaiveEventListener listener = new NaiveEventListener(source);

source.Raise();

Console.WriteLine("Setting listener to null.");
listener = null;

TriggerGC();

source.Raise();

Console.WriteLine("Setting source to null.");
source = null;

TriggerGC();

Here is the output:

EventListener received event.
Setting listener to null.
Starting GC.
GC finished.
EventListener received event.
Setting source to null.
Starting GC.
NaiveEventListener finalized.
GC finished.

Let’s analyze the workflow:

  • EventListener received event.“: This is the consequence of our call to “source.Raise()”; perfect, seems like we’re listening.
  • Setting listener to null.“: We nullify the reference that the current local context holds to the event listener object, which should allow garbage collection of the listener.
  • Starting GC.“: Garbage collection starts.
  • GC finished.“: Garbage collection ends, but our event listener object has not been reclaimed by the garbage collector, which is proven by the fact its finalizer has not been called
  • EventListener received event.“: This is confirmed by the second call to “source.Raise()”, the listener is still alive!
  • Setting source to null.“: We nullify the reference to the event source object.
  • Starting GC.“: The second garbage collection starts.
  • NaiveEventListener finalized.“: This time, our naive listener is collected, better late than never.
  • GC finished.“: The second garbage collection ends.

Conclusion: Indeed, there is a hidden strong reference to the listener which prevents the event listener to be collected as long as the event source is not collected!

Hopefully, there is a standard solution for this issue: the event source can reference the listener through a weak reference, which won’t prevent collection of the listener even if the source is still alive.

And there is a standard pattern and its implementation in the .NET Framework: the weak event pattern.

The Weak Event Pattern

So let’s see how we can tackle the issue in the .NET Framework.

As often there is more than one way to do it, but in this case, the decision process is quite straightforward:

  • if you’re using .NET 4.5, you can benefit from a simple implementation
  • otherwise, you’ll have to rely on a slightly more contrived approach

The Legacy Way

Before .NET 4.5, the .NET Framework came with a class and an interface that allowed implementation of the weak event pattern:

  • WeakEventManager which is where all the pattern plumbing is encapsulated
  • IWeakEventListener which is the pipe that allows a component to connect to the WeakEventManager plumbing

(Both are located in the WindowsBase assembly that you’ll need to reference yourself if you’re not developing a WPF project which should already correctly reference it.)

So this is a two step process.

First, you implement a custom event manager by specializing the WeakEventManager class:

  • you override the StartListening and StopListening methods that respectively registers a new handler and unregisters an existing one; they will be used by the WeakEventManager base class itself
  • you provide two methods to give access to the listeners list, typically named “AddListener” and “RemoveListener “, that are intended for the users of your custom event manager
  • you provide a way to get an event manager for the current thread, typically by exposing a static property on your custom event manager class

Then, you make your listener class implement the IWeakEventListener interface:

  • you implement the ReceiveWeakEvent method
  • you try to handle the event
  • you return true if you’ve been able to handle the event correctly

This is a lot of words, but it translates to relatively few code:

First, the custom weak event manager:

C#
public class EventManager : WeakEventManager
{
    private static EventManager CurrentManager
    {
        get
        {
            EventManager manager = (EventManager)GetCurrentManager(typeof(EventManager));

            if (manager == null)
            {
                manager = new EventManager();
                SetCurrentManager(typeof(EventManager), manager);
            }

            return manager;
        }
    }

    public static void AddListener(EventSource source, IWeakEventListener listener)
    {
        CurrentManager.ProtectedAddListener(source, listener);
    }

    public static void RemoveListener(EventSource source, IWeakEventListener listener)
    {
        CurrentManager.ProtectedRemoveListener(source, listener);
    }

    protected override void StartListening(object source)
    {
        ((EventSource)source).Event += DeliverEvent;
    }

    protected override void StopListening(object source)
    {
        ((EventSource)source).Event -= DeliverEvent;
    }
}

Then our event listener:

C#
public class LegacyWeakEventListener : IWeakEventListener
{
    private void OnEvent(object source, EventArgs args)
    {
        Console.WriteLine("LegacyWeakEventListener received event.");
    }

    public LegacyWeakEventListener(EventSource source)
    {
        EventManager.AddListener(source, this);
    }

    public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
    {
        OnEvent(sender, e);

        return true;
    }

    ~LegacyWeakEventListener()
    {
        Console.WriteLine("LegacyWeakEventListener finalized.");
    }
}

Let’s check it:

C#
Console.WriteLine("=== Legacy weak listener (better) ===");

EventSource source = new EventSource();

LegacyWeakEventListener listener = new LegacyWeakEventListener(source);

source.Raise();

Console.WriteLine("Setting listener to null.");
listener = null;

TriggerGC();

source.Raise();

Console.WriteLine("Setting source to null.");
source = null;

TriggerGC();

Results:

LegacyWeakEventListener received event.
Setting listener to null.
Starting GC.
LegacyWeakEventListener finalized.
GC finished.
Setting source to null.
Starting GC.
GC finished.

Nice, it works, our event listener object is now correctly finalized during the first GC though the event source object is still alive, no more leak.

But this is quite a bunch of code to write for a simple listener, imagine you have dozens of such listeners, you’d have to write a new weak event manager for each type!

If you are fluent with code refactoring and generics, you may have found a clever way of refactoring all this common code.

Before .NET 4.5, you had to implement this clever weak event manager yourself, but now .NET provides a standard solution for this issue, and we’ll review it right now!

The .NET 4.5 Way

.NET 4.5 has introduced a new generic version of the legacy WeakEventManager: WeakEventManager<TEventSource, TEventArgs>.

(This class is located in the WindowsBase assembly too.)

Thanks to a good use of .NET generics, the WeakEventManager<TEventSource, TEventArgs> handles genericity itself, without us having to reimplement a new manager for each event source.

As a consequence, the resulting code is far lighter and readable:

C#
public class WeakEventListener
{
    private void OnEvent(object source, EventArgs args)
    {
        Console.WriteLine("WeakEventListener received event.");
    }

    public WeakEventListener(EventSource source)
    {
        WeakEventManager<EventSource, EventArgs>.AddHandler(source, "Event", OnEvent);
    }

    ~WeakEventListener()
    {
        Console.WriteLine("WeakEventListener finalized.");
    }
}

There is only a single line of code to write, really clean.

The usage is similar to the other implementations, as all the stuff has been encapsulated into the event listener class:

C#
Console.WriteLine("=== .Net 4.5 weak listener (best) ===");

EventSource source = new EventSource();

WeakEventListener listener = new WeakEventListener(source);

source.Raise();

Console.WriteLine("Setting listener to null.");
listener = null;

TriggerGC();

source.Raise();

Console.WriteLine("Setting source to null.");
source = null;

TriggerGC();

And just to be sure it works as advertised, here is the output:

WeakEventListener received event.
Setting listener to null.
Starting GC.
WeakEventListener finalized.
GC finished.
Setting source to null.
Starting GC.
GC finished.

As expected, the behavior is the same as the legacy event manager, what more could we ask for?!

Conclusion

As you’ve seen, implementing the weak event pattern in .NET is quite straightforward, particularly with .NET 4.5.

If you’re not using .NET 4.5, as the implementation requires some boilerplate code, you may be tempted to not use this pattern and instead directly use the C# language facilities (+= and -=), and see if you have any memory issue, and only if you notice some leaks, then make the necessary effort of implementing it.

But with .NET 4.5, as it’s almost free, the plumbing code being managed by the framework, you can really use it in the first place, though it’s a little less cool than the C# syntax “+=” and “-=” but semantics is equally clear, and this is what matters.

I’ve done my best to be technically accurate and avoid any spelling errors but if you catch any typo or mistake, have some issue with the code or have additional questions, feel free to leave a comment.

History

  • 3rd March, 2014: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Instructor / Trainer Pragmateek
France (Metropolitan) France (Metropolitan)
To make it short I'm an IT trainer specialized in the .Net ecosystem (framework, C#, WPF, Excel addins...).
(I'm available in France and bordering countries, and I only teach in french.)

I like to learn new things, particularly to understand what happens under the hood, and I do my best to share my humble knowledge with others by direct teaching, by posting articles on my blog (pragmateek.com), or by answering questions on forums.

Comments and Discussions

 
QuestionRelease listener without Garbage Collection Pin
Francois Botha5-May-16 4:55
Francois Botha5-May-16 4:55 
I have a few hundred thousand listeners and want to implement the WeakEvent pattern. However, even after implementing it, it seems the only way to release the listener is to call TriggerGC(), which is quite a degradation on performance. If I leave the TrggerGC() until the very end (after I'm finished with all my listeners), then the WeakEvent pattern doesn't do much; all the thousands of listeners still keep receiving events (which also result in a fairly costly exercise - recalculating a lot of values) and they're released only at the very end.

Maybe this is just an effect of .NET garbage collection which I don't fully understand yet, but I'd appreciate some tips in this regard.
AnswerRe: Release listener without Garbage Collection Pin
Pragmateek11-May-16 10:51
professionalPragmateek11-May-16 10:51 
GeneralRe: Release listener without Garbage Collection Pin
Skullsplitter29-Aug-16 19:43
Skullsplitter29-Aug-16 19:43 
GeneralRe: Release listener without Garbage Collection Pin
Pragmateek25-Oct-16 11:28
professionalPragmateek25-Oct-16 11:28 
QuestionGreat article Pin
Member 124238152-May-16 22:58
Member 124238152-May-16 22:58 
AnswerRe: Great article Pin
Pragmateek11-May-16 10:37
professionalPragmateek11-May-16 10:37 
GeneralMy vote of 5 Pin
noshirwan15-Aug-14 11:14
noshirwan15-Aug-14 11:14 
GeneralRe: My vote of 5 Pin
Pragmateek15-Aug-14 11:39
professionalPragmateek15-Aug-14 11:39 
QuestionWhen do I call WeakEventManager<TEventSource, TEventArgs>.RemoveHandler(...)? Pin
David E. Battey16-Jul-14 5:29
David E. Battey16-Jul-14 5:29 
AnswerRe: When do I call WeakEventManager<TEventSource, TEventArgs>.RemoveHandler(...)? Pin
Pragmateek16-Jul-14 6:05
professionalPragmateek16-Jul-14 6:05 
QuestionEventSource does not have Event Property? Pin
coinci26-Mar-14 20:21
coinci26-Mar-14 20:21 
AnswerRe: EventSource does not have Event Property? Pin
Pragmateek27-Mar-14 0:12
professionalPragmateek27-Mar-14 0:12 
GeneralRe: EventSource does not have Event Property? Pin
coinci27-Mar-14 16:53
coinci27-Mar-14 16:53 
GeneralRe: EventSource does not have Event Property? Pin
Pragmateek28-Mar-14 0:13
professionalPragmateek28-Mar-14 0:13 
GeneralRe: EventSource does not have Event Property? Pin
GNovotny27-May-15 6:08
GNovotny27-May-15 6:08 
GeneralRe: EventSource does not have Event Property? Pin
Pragmateek27-May-15 8:41
professionalPragmateek27-May-15 8:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.