pondělí 8. června 2015

C# Safe Event Pattern

C# language has a very good support for event programming. However, is does not address a two common issues with event handlers:
  1. An event handler is registered more times, but we want to call it just once.
  2. An event handler is registered from longer living object then the event source. Then the event handler must be unregistered. Otherwise it may cause memory leaks.
First issue is usually simple to solve. The memory leaks are best avoided when using weak references. There are several solutions to .NET weak event references. e.g. see The .NET weak event pattern in C#. I have decided to go with .NET 4.5 WeakEventManager. The following pattern makes it easy for MyEvent consumer to write the code without worrying about event handler unregistering.
private event MyEventArgs _myEvent;

public event EventHandler<MyEventArgs> MyEvent
        // first unregister if registered
        MyEvent-= value;
        // register
        WeakEventManager<ThisType, MyEventArgs>.AddHandler(_myEvent, "MyEvent", value);
        WeakEventManager<ThisType, MyEventArgs>.RemoveHandler(_myEvent, "MyEvent", value);