Tagged: Rx

Interesting Web Dev Things 9 Jul 2014


Managed leak from event subscription? – Use Rx and WeakReference

The problem is well known in .Net development (Have a look at Dustin Campbell’s blog on the problem); a form subscribes to some event, the form is closed, but never gets garbage collected because it maintains a strong reference to the publisher. The obvious solution is explicitly unsubscribing from the event in the dispose. Another more automated approach is to use the Reactive Framework (Rx) as shown on Samuel Jack’s blog.

If you just want to jump straight into debugging an example you can simply create a new console project, add Rx via Nuget and replace the main block with this (essentially all the code from Samuel’s article). The key things to take away is (and you can break to watch it happen in realtime):

1) The target is held as a WeakReference – if it’s still alive when the event occurs it’s passed to the subscriber, if not the subscription is removed.

2) The handler passed in to the SubscribeWeakly must call instance methods via the reference to the target, rather than using the implicity this. i.e. target.HandleEvent(item) not HandleEvent(item) – otherwise you’ll have a strong reference (class instance) to the target.

3) Wrap your events  into an IObservable using Observable.FromEventPattern. More details on briding .Net events to observable sequences can be found here.