Tuesday, February 05, 2013

.NET Weak Events for the Busy Programmer

Introduction

By now we are all familiar with delegates in .NET. They are so simple yet so powerful. We use them for events, callbacks, and many other wonderful derivative functions. However delegates have a nasty little secret. When you subscribe to an event, the delegate backing that event will keep a strong reference to you. What does this mean? It means that you (the caller) will not be able to be garbage collected since the garbage collection algorithm will be able to find you. Unless you like memory leaks this is a problem. This article will demonstrate how to avoid this issue without forcing callers to manually unsubscribe. The aim of this article is make using weak events extremely simple.

Background

Now I've see my share of weak event implementations. They more or less do the job including the WeakEventManager in WPF. The issue I always encountered is either their setup code or memory usage. My implementation of the weak event pattern will address memory issues and will be able to match any event delegate signature while making it very easy to incorporate into your projects. 

Implementation

The first thing developers should know about delegates is that they are classes just like any other .Net class. They have properties that we can use to create own own weak events. The issue with the delegate as I mentioned before is that they keeps a strong reference to the caller. What we need to do is to create a weak reference to the caller. This is actually simple. All we have to do is use a WeakReference object to accomplish this.

RuntimeMethodHandle mInfo = delegateToMethod.Method.MethodHandle;
 
if (delegateToMethod.Target != null)
{
  WeakReference weak = new WeakReference(delegateToMethod.Target);
  subscriptions.Add(weak, mInfo);
}
else
{
  staticSubscriptions.Add(mInfo);
}

In the above example 'delegateToMethod' is our delegate. We can get to the method that it will eventually invoke and most importantly we can get to it's Target, the subscriber. We then create a weak reference to the target. This allows the target to the garbage collected if it is no longer in scope.

Read more: Codeproject
QR: Inline image 1

Posted via email from Jasper-Net