Monday, 19 March 2012

Weak Events in .Net, the easy way

I’ve written before about one kind of memory leak the .Net Garbage Collector cannot protect against: those caused by event handlers keeping objects alive beyond their best-before date. Daniel Grunwald has a very comprehensive article on CodeProject explaining the problem in depth, and giving a number of solutions, some of which I’ve used in the past.

Nowadays, my preferred solution is one made possible by the fabulous Reactive Extensions (Rx) framework.

Suppose, as one example, you want to subscribe to a CollectionChanged event, but don’t want your object to be kept alive by that subscription. You can just do:

collection.ObserveCollectionChanged()
          .SubscribeWeakly(this, (target, eventArgs) => target.HandleEvent(eventArgs));

private void HandleEvent(NotifyCollectionChangedEventArgs item)
{
    Console.WriteLine("Event received by Weak subscription");
}

How it works

Like all remedies for un-dying object problems, the active ingredient in this one is the WeakReference class. It works like this

public static class IObservableExtensions
{
    public static IDisposable SubscribeWeakly<T, TTarget>(this IObservable<T> observable, TTarget target, Action<TTarget, T> onNext) where TTarget : class 
    {
        var reference = new WeakReference(target);

        if (onNext.Target != null)
        {
            throw new ArgumentException("onNext must refer to a static method, or else the subscription will still hold a strong reference to target");
        }

        IDisposable subscription = null;
        subscription = observable.Subscribe(item =>
                                                    {
                                                        var currentTarget = reference.Target as TTarget;
                                                        if (currentTarget != null)
                                                        {
                                                            onNext(currentTarget, item);
                                                        }
                                                        else
                                                        {
                                                            subscription.Dispose();
                                                        }
                                                    });

        return subscription;
    }
}

You can see that we hold the intended recipient of the notifications, target, as a WeakReference, so that if the Garbage Collector wants to sweep it up, this subscription won’t stand in its way. Then we subscribe a lambda function of our own to the observable. When we receive a notification from the observable, we check that target is still alive, and then pass along the message. If we discover that target has died, we mourn briefly, then cancel the subscription.

Notice though, that all our clever use of WeakReferences could be subverted if the onNext delegate refers to an instance method on the target. That delegate would then be smuggling in the implicit this pointer as a strong reference to the target. onNext is itself held strongly by the closure that is created for the lambda function, so the net effect would be that the target is kept alive by the subscription.

All of which explains why we do a check to ensure that onNext.Target is null, hence, that onNext is referring to a static method.

To be clear, this doesn’t mean that you can only handle events using static methods. It just means that when you call SubscribeWeakly, the lambda function you supply as onNext must call instance methods via the reference to the target it is given as a parameter (like I showed in the example above) rather than capturing an implicit this reference.

Observing .Net events using Rx

If you’re going to start using this, you’ll need to know how to turn .Net events into IObservables. Fortunately, the Rx framework includes a magic wand in the shape of Observable.FromEventPattern.

Working with events that have been coded-up post-generics, and thus use EventHandler<TEventArgs> delegates, is easiest. Here’s how you would observe the TaskScheduler.UnobservedTaskException event, for example:

Observable.FromEventPattern<UnobservedTaskExceptionEventArgs>(
                handler => TaskScheduler.UnobservedTaskException += handler,
                handler => TaskScheduler.UnobservedTaskException -= handler);

You simply instruct Rx how to attach and detach the event handler it supplies.

Events defined pre-generics all had to roll their own delegate types, and that makes observing them 1-line-of-code more difficult. Here’s the definition of ObserveCollectionChanged which I used earlier:

public static IObservable<EventPattern<NotifyCollectionChangedEventArgs>> ObserveCollectionChanged(this INotifyCollectionChanged collection)
{
    return Observable.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
        handler => (sender, e) => handler(sender, e),
        handler => collection.CollectionChanged += handler,
        handler => collection.CollectionChanged -= handler);
}

What’s happening here, in the first parameter to FromEventPattern, is that we are adapting an event handler delegate in standard form (i.e EventHandler<NotifyCollectionChangedEventArgs>) given to us by Rx into one appropriate for this specific event. In fact, the compiler is doing all the work, inferring the necessary types of the delegates for us. Then, as before, we show Rx how to hook the adapted handler up to the appropriate event, and how to detach when the subscription is cancelled.

Prove It

To prove this all works as it should, I’ve created a little test:

class Program
{
    static void Main(string[] args)
    {
        var collection = new ObservableCollection<object>();

        var strongSubscriber = new StrongSubscriber();
        strongSubscriber.Subscribe(collection);

        var weakSubscriber = new WeakSubscriber();
        weakSubscriber.Subscribe(collection);

        collection.Add(new object());

        strongSubscriber = null;
        weakSubscriber = null;

        GC.Collect();
        Console.WriteLine("Full collection completed");

        collection.Add(new object());

        Console.Read();
    }

    private class StrongSubscriber
    {
        public void Subscribe(ObservableCollection<object> collection)
        {
            collection.CollectionChanged += delegate { Console.WriteLine("Event Received By Strong Subscription"); };
        }
    }

    private class WeakSubscriber
    {
        public void Subscribe(ObservableCollection<object> collection)
        {
            collection.ObserveCollectionChanged().SubscribeWeakly(this, (target, item) => target.HandleEvent(item));
        }

        private void HandleEvent(EventPattern<NotifyCollectionChangedEventArgs> item)
        {
            Console.WriteLine("Event received by Weak subscription");
        }
    }
}

In the blue corner we have StrongSubscriber who subscribes to an event on a collection the standard way. And in the red corner we have WeakSubscriber who listens to events using SubscribeWeakly. We trigger an event to show that both are paying attention, then we attempt to nuke them, setting their references to null and doing a full garbage collection. Finally, we trigger another event, to see who survived the apocalypse. Here’s the result:

image

As expected, the StrongSubscription clung on to life, whilst the WeakSubscription dutifully died.

Here – take it!

As with all the code on my blog, feel free to take this and use it in your own projects. I’d love to hear how you get on with it.

5 comments:

Pradeep Sweetball said...

Thank You

The given information is very effective
i will keep updated with the same 

industrial automation

Rob Vickers said...

Trying to adapt your code to my own project - didn't you have to make HandleEvent static in order for it to work?  Otherwise, wouldn't the onNext.Target != null return true when you called SubscribeWeakly()?

Rob Vickers said...

Never mind - I answered my own question when I realized that even my static method had a non-null target when I passed an action through.  Need to work just with the event args I guess.

deep sengupta said...

What if you don't call GC.Collect(); will your code work. I have a similar situation where I can't call GC.Collect() but expect that my weakSubscription won't be called.

Samuel Jack said...

Yes, it will still work. GC.Collect() is only there to force a garbage collection at that particular point in code, so that I can prove that weak event handlers have been unsubscribed. Normally, automatic garbage collection will do exactly the same job.

Post a Comment