Thursday, April 4, 2013

Sasa.Events - Type-Safe, Null-Safe, Thread-Safe Events

This is the twelfth post in my ongoing series covering the abstractions in Sasa. Previous posts:

It's well-known by now that the CLR's event model is a little broken. It requires clients using events to handle corner cases that should be handled by the runtime, particularly thread-safe event mutation and null-safe event invocation. Eric Lippert describes the issues.

Sasa.Events is a static class providing methods achieving just that. It makes mutating events/delegates thread-safe (#1 thread-safety from Eric's article), and makes invocation null-safe.

Sasa.Events.Add

Sasa.Events.Add is a static method that takes a reference to an event type T and adds a new delegate of type T to that event in a thread-safe way without using locks. Typically, a public event declared in C# causes the C# compiler to create a hidden field of type System.Object, and to perform a lock on that object before modifying the event:

public class Foo
{
  public event EventHandler SomeEvent;
}

Translates into:

public class Foo
{
  EventHandler _someEvent;
  object _someEventLock = new object();
  public EventHandler SomeEvent
  {
    add { lock (_someEventLock) _someEvent += value; }
    remove { lock(_someEventLoc) _someEvent -= value; }
  }
}

Of course, being an immutable value, a multicast delegate doesn't need locks for mutation, we can just perform a lock-free, atomic compare-exchange in a loop until it succeeds:

public class Foo
{
  EventHandler _someEvent;
  public EventHandler SomeEvent
  {
    add { for (var e = _someEvent; e != Interlocked.CompareExchange(ref _someEvent, Func.Combine(_someEvent, value), e); e = _someEvent); }
    remove { for (var e = _someEvent; e != Interlocked.CompareExchange(ref _someEvent, Func.Remove(_someEvent, value), e); e = _someEvent); }
  }
}

This is both faster, and doesn't waste memory. Sasa.Events.Add performs exactly the above:

EventHandler _someEvent;
...
Events.Add(ref _someEvent, (o,e) => ...);

So instead of the shorthand event notation used in C#, just declare a delegate field and add the add/remove handlers like so:

public class Foo
{
  EventHandler _someEvent;
  public EventHandler SomeEvent
  {
    add { Events.Add(ref _someEvent, value); }
    remove { Events.Remove(ref _someEvent, value); }
  }
}

Sasa.Events.Clear

Sasa.Events.Clear clears out the entire list of event handlers, and returns the original contents:

EventHandler _someEvent;
...
var x = Events.Clear(ref _someEvent);
// _someEvent is now null, and x has the original contents
x.Raise();

I often use something like the above for thread-safe, lock-free disposal patterns.

Sasa.Events.Raise

Sasa.Events.Raise are a set of extension methods on various delegate types that provide null-safe event raising. In other words, C# developers no longer have to manually implement the following pattern:

event Action SomeEvent;
...
var someEvent = SomeEvent;
if (someEvent != null) someEvent();

Instead, they can simply call SomeEvent.Raise():

event Action SomeEvent;
event EventHandler OtherEvent;
...
SomeEvent.Raise();
OtherEvent.Raise(EventArgs.Empty);

Note that Raise is only supported for a core set of delegate types:

  • All event handler delegates under System namespace
  • All System.Action* delegates
  • All event handler delegates under System.ComponentModel

I could certainly be persuaded to add more overloads for other cases, so if you want some added, speak up!

Sasa.Events.RaiseAny

Since not all delegate types can be included in Sasa.Events, and because delegates are typed nominally instead of structurally, we have Sasa.Events.RaiseAny, which takes an array of object parameters and performs a thread-safe dynamic runtime invocation of the event:

delegate void Foo(string arg0, int arg1);
...
event Foo FooEvent;
...
FooEvent.Raise("first arg", 3);

Sasa.Events.Remove

The complementary operation to Sasa.Events.Add, Sasa.Events.Remove performs a type-safe, thread-safe event mutation without locks:

EventHandler _someEvent;
...
Events.Remove(ref _someEvent, (o,e) => ...);

No comments: