As long as an object in the .NET Framework is
somehow referenced, it is not disposed of by the garbage collector. An
object can be referenced not only by variables but also by delegates.
type1.MyEvent += type2.MyEventRaised;
Even if no variable refers to the type2 object in the preceding example, because of the registered callback method, the type2 object is still referenced by type1. The type2 object can be disposed of only after type1 is.
If you want to be able to dispose of type2 as soon as no variable points to it, without having to remove the event handler manually with the minus operator (−=), use the WeakDelegate class. This class is only available in the .NET Micro Framework and, therefore, in the Microsoft.SPOT
namespace. No changes are visible on the interface for the users of a
class with weak delegates. You only need to change the implementation
of the event in the Type1 class. In order to use a weak delegate instead of a strong delegate, Type1 must look as it does in Listing 1.
Example 1. A Class with a Weak Delegate
internal sealed class Type1 { //the prototype of MyEvent's callback methods public delegate void MyEventHandler(Object sender, String s);
//a private field for the (weak) delegates private MyEventHandler myEvent;
//weak delegate public event MyEventHandler MyEvent { [MethodImpl(MethodImplOptions.Synchronized)] Add { //Combine turns the delegate referred to by value into a weak delegate this.myEvent = (MyEventHandler)WeakDelegate.Combine(this.myEvent, value); }
[MethodImpl(MethodImplOptions.Synchronized)] Remove { //Remove deletes the delegate referred to by value from the delegate chain this.myEvent = (MyEventHandler)WeakDelegate.Remove(this.myEvent, value); } } }
|
When registering and removing a callback method from the list with linked event handlers, you have to call the static methods Combine and Remove of the WeakDelegate class.
The WeakDelegates sample project included in the .NET Micro Framework SDK demonstrates the use of weak delegates. |