A place for spare thoughts


Weak delegates for non-standard event handlers (e.g. WPF)

Filed under: wpf — Ivan Danilov @ 14:04

About Weak delegates there’s many articles lurking around the Internet. The most beautiful IMO is this one. So, I assume that you already read it and won’t repeat that info.

So, some time ago (pretty much time, actually, just hadn’t time to write earlier), inspired by the beauty of the article I happily copied MakeWeak extension method to our codebase… just to find out that the most frequently used WPF event is declared as

event PropertyChangedEventHandler PropertyChanged;

public delegate void PropertyChangedEventHandler(object sender,
                                                 PropertyChangedEventArgs e);

Remember Dustin’s complaints about MS not following their own recommendations? That’s it. Problem. Why is it not declared as that?

event EventHandler<PropertyChangedEventArgs> PropertyChanged;

Who knows? I’m interested too. Can’t see any problems and one type to load less for CLR. But anyway, if I want to work with WPF – I should invent something about the problem.

And so the saga begins… oops, it is not from this story, sorry πŸ™‚

So, lets define first what our weak events MUST HAVE (i.e. without what they wouldn’t be useful at all). For me these requirements include at least:

  • It should be weak and should be working! (surprise, eh?)
  • I shouldn’t specify type parameters explicitly, they should be fully inferred from usage;
  • I want static check that actual unsubscription is correctly typed and I don’t unsubscribe delegate of wrong type (so, basically I want be at least minimally defended against InvalidCaseException at runtime);
  • Performance should be at least the same order as with normal delegates, i.e. no hardcore reflection on every event invocation.

The very first problem is to obtain original event actually. Originally MakeWeak defined as

public static EventHandler<TEventArgs> MakeWeak<TEventArgs>(
        this EventHandler<TEventArgs> eventHandler,
        UnregisterCallback<TEventArgs> unregister)
    where TEventArgs : EventArgs

See the problem? With non-standard delegates we don’t have EventHandler<TArgs>. And we have to save that delegate later after ‘casting’ it to OpenEventHandler in the WeakEventHandler class – there we need MethodInfo instance that originally obtained via eventHandler.Method property. So the idea – lets parametrize this method with one yet type parameter, like that:

public static EventHandler<TEventArgs> MyMakeWeak<THandler, TEventArgs>(
        this EventHandler<TEventArgs> eventHandler,
        UnregisterCallback<TEventArgs> unregister)
    where THandler : Delegate
    where TEventArgs : EventArgs

So we pass eventHandler and Delegate has Method property as well, so it should be fine… nope, it’s not. If you try to compile that you have “Constraint cannot be special class ‘System.Delegate'” from compiler. Eric Lippert said that there’s no technical reason to not support such syntax, but it is just not needed often, so it is pretty low on priority list. No luck! I have to thought out something else.

OK, let’s sacrifice type safety here and make extension method accept any type T:

TEventHandler MyMakeWeakTEventHandler>(this TEventHandler eventHandler, 
                                       Action<TEventHandler> unregister)

It is not a big deal and doesn’t break our requirement – remember, we will use this method only with that syntax:

obj.PropertyChanged += new PropertyChangedEventHandler(MyMethod)
    .MyMakeWeak(h => obj.PropertyChanged -= h);

In other words, if we try to pass not PropertyChangedEventHandler but some wrong class there, it will violate types at += operator because we’re returning exactly that type that was passed to our extension method.

So, what will we have then? We can rely on the fact that TEventHandler in reality is derived from Delegate class and can be cast to it. Yes, it is possible to misuse that method and get exception at runtime only, but it is hard to do unintentionally, so I’m fine with that.

The next problem: we don’t know argument type from the start. Before it was TEventArgs : EventArgs, but now we don’t have such thing. Well, if we can cast our param to Delegate – we can know list of its parameters via Delegate.Method.GetParameters()[index].ParameterType. Not very pretty and we don’t know concrete signature of the delegate – even number of parameters… Wait, we do know number of parameters almost always – fortunately, WPF team didn’t abandon guidelines totally and their delegates have normal void (object sender, TEventArgs e) signature everywhere. That’s something. Yep, again, it won’t work absolutely everywhere, but in worst case I can extend this approach in the same ugly way as Func can have various number of type arguments (no, I will not do this here because I don’t need this – at least I haven’t so far).

So, MyWeakEventHandler will have one generic type parameter more as it needs to know not only receiver type and event args type, but exact delegate type as well.

So far, so good. It seems everything is pretty much clear with MyMakeWeak method – at least if it will work in the end (remember first requirement?). And one last stroke: instead of strange MyMakeWeak I finally named it MakeWeakSpecial. While I could name it MakeWeak too as original one (which stays untouched) it would bring to scene C#’s overload resolution rules which are insanely complex and sometimes very confusing in the presence of generics. So I’ve decided to name it differently just to be sure what I’m using. Here’s what we have:

public static TEventHandler MakeWeakSpecial<TEventHandler>(this TEventHandler eventHandler, Action<TEventHandler> unregister)
    if (eventHandler == null)
        throw new ArgumentNullException("eventHandler");

    var ehDelegate = (Delegate) (object) eventHandler;
    var eventArgsType = ehDelegate.Method.GetParameters()[1].ParameterType;
    Type wehType = typeof(WeakEventHandlerSpecial<,,>)

    ConstructorInfo wehConstructor = wehType.GetConstructor(new[]

    Debug.Assert(wehConstructor != null, "Something went wrong. There should be constructor with these types");

    var weh = (IWeakEventHandlerSpecial<TEventHandler>)wehConstructor
        .Invoke(new object[] 
                    (Action<object>)(o => unregister((TEventHandler) o)) 

    return weh.Handler;

Well, lets go to WeakEventHandlerSpecial<T, TEventHandler, TEventArgs>. The only problem we have there is that TEventHandler has no relation to TEventArgs. So, original concise _handler = Invoke; is not applicable, as _handler has type TEventHandler and Invoke is method group with (object, TEventArgs) signature. It is not hard problem: we just need to obtain current instance’s type, find its method "Invoke" and dynamically create delegate of type TEventHandler with Delegate.CreateDelegate. And what about performance, you could ask? Well, it is another costly operation. But we’re still in the code region that will be executed once for a subscription, NOT once per event occurring. So I deem it reasonable (Again, in the worst case if I need to optimize these at some point – nobody prevents me from some caching strategy or creating compiled Expression or any other mechanism – thus, from ‘once per subscription’ it will be ‘once per given three types’).

And so, finally, here you can get results (WeakDelegates.zip) with several unit tests: link.

And in case you don’t want to download something and want just a quick-look at what I have as result – you have this gist.

And regarding requirements:

1. It’s working. Unit tests are swearing that it is so.
2. While using I’m not forced to specify anything.
3. In the only real-world usage types are checked. Other cases are not, but it is ok.
4. There’s somewhat more reflection than it was in the original weak events, but only slightly.

I think my own requirements are pretty much fulfilled. πŸ™‚


1 Comment »

  1. […] time ago I wrote about weak events including non-standard ones. While this post is not totally dependent on weak events, I will assume […]

    Pingback by WeakEvents catch with tests | A place for spare thoughts — 17/04/2013 @ 19:01

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: