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:

          .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);

        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:

                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();

        var weakSubscriber = new WeakSubscriber();

        collection.Add(new object());

        strongSubscriber = null;
        weakSubscriber = null;

        Console.WriteLine("Full collection completed");

        collection.Add(new object());


    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:


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.

Wednesday, 14 March 2012

Solved: Http Error returned for some route urls but not others in Asp.Net MVC or Web API

Here GoogleBing: remember this one for me so I don’t have to waste another two hours re-solving it.

I’m working on a project using the new Asp.Net Web API and hit a really strange problem yesterday. Every time I called the /search endpoint, I’d get back a Http Error 404.20 – Not Found. All the other controllers were working fine. There were no exceptions being thrown and, even stranger, if I set a break point in the SearchController it was never hit.

I spent two hours trying every which-way to get to the bottom of it.

The light-bulb lit up when my eye latched on to this:

image(No, that’s not Visual Studio 11. I just faded all the rest to grey so you could see what I saw).

There in the solution was a folder with the same name as the Web API Controller. A quick test confirmed that any route with the same url as a folder in my solution would give the same error.

The Solution

There’s the obvious solution: rename either your folder or your controller, so that there’s no conflict.

But if you’re rather attached to your Controller name, and you’re loath to change your folder structure, there is another solution. When you register your Routes, set

RouteTable.Routes.RouteExistingFiles = true;

This makes Asp.Net Routing try the routes in your RouteTable first, even if there are files and directories that match them.

This by itself was enough for us, because we don’t have any files on disk that we want to serve up directly. But if you do, add


for each folder that you want to serve up, and everything should by hunky-dory.

Monday, 12 March 2012

Fade-Trimming TextBlocks in Silverlight and WPF

Ayende just published a guest-post I wrote on his company blog:

Using ellipsis is so last year. When did you last see the cool HTML 5 kids writing … when they couldn’t fit all their text in a column? They’ve got this fancy new feature, powered by CSS3, where text that doesn’t quite fit simply fades out as it reaches the edge of the text block. Like this (with thanks to the QuickUI Catalog)


Subtle! It looks much prettier, and it means you can fit in an extra three characters of real text instead of the …s.

Silverlight’s future might be uncertain, but I want to show you that it isn’t ready to roll over and die just yet. We can have those fancy fade-trimming effects too!

As part of the work I’m doing on the UI for RavenFS, I implemented Fade-trimming to make our DataGrids look smarter, and I thought it would be nice to share. So I’ve packaged up all you need into an easy-to-use class called FadeTrimming.cs which works in Silverlight and WPF, and given you two demo projects to show you how to get started.

Read the whole article here