Weak events

Introduction

When using usual C# events, registering an event handler creates a strong reference from the event source to the listening object. If the source object has a longer lifetime than the listener, and if the listener no longer needed (there are no other references), to avoid memory leak the listener object must unsubscribe from the source event, if it does not, the use normal .NET events causes a memory leak.There are lots of different approaches to resolve this problem. This article will explain some of them and discuss their advantages and disadvantages.

Method 1. Using weak-delegate without code-generation.

This method is very simple, we need to create wrapper for a weak-delegate:

Method 2. Using weak-delegate created by DynamicMethod.

The second method uses the DynamicMethod to generate a weak version of delegate. The code below demonstrates one approach to generate weak delegate using emit.The first step it's create class that represents a information about weak event:

Conclusion

If you do not need the high performance you can use the first method, otherwise, your choice will be the second or the third method. The third method can work in partial trust, which is very important if you are using Silverlight.Moreover, there are lots of different approaches to this problem and this article explain a few of them.