Another WeakEvent paradigm RRS feed

  • General discussion

  • Hello there,

    I'd love to hear what you all think of my new weak event handling mechanizm.

    The idea is to create an "EventHandle" object that represents a subscription to an event. When this handle is collected by gc (or disposed manually) the event handler is removed.

    Here's how you use it:

    // Subscribe to any type of event
    this.Handle = EventHandle.Create(
    	(t, h) => t.PropertyChanged += h,
    	(t, h) => t.PropertyChanged -= h);
    // Or use extension methods for specific types of events
    this.Handle = target.SubscribePropertyChanged(callback, "PropertyName");
    // Unsubscribe

    The handle and callback are collectible because the callback is not directly attached to the target event, instead a proxy event handler is created that forwards events to a weak reference of the callback.

    You can find the source here

    There are lots of improvements that could be made. Currently the EventHandle class always holds a strong reference to the target (event source) but it wouldn't be hard to modify the code to always or optionally hold a weak reference to the target.

    Feed back would be greatly appreciated, is there a reason why I haven't seen this done before?


    Tuesday, July 3, 2012 3:43 PM

All replies

  • If you look into Reactive Extensions this is exactly what they do!  Very cool stuff indeed.

    JP Cowboy Coders Unite!

    Tuesday, July 3, 2012 6:05 PM
  • Cheers Javaman, slightly disappointed its not a completely new idea :p. At least the concept has been tried and tested. Here's a new version, I made some mistakes refactoring the code for pastebin. Joe

    Wednesday, July 4, 2012 9:33 AM