Skip to main content

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) => ...);

Comments

Popular posts from this blog

async.h - asynchronous, stackless subroutines in C

The async/await idiom is becoming increasingly popular. The first widely used language to include it was C#, and it has now spread into JavaScript and Rust. Now C/C++ programmers don't have to feel left out, because async.h is a header-only library that brings async/await to C! Features: It's 100% portable C. It requires very little state (2 bytes). It's not dependent on an OS. It's a bit simpler to understand than protothreads because the async state is caller-saved rather than callee-saved. #include "async.h" struct async pt; struct timer timer; async example(struct async *pt) { async_begin(pt); while(1) { if(initiate_io()) { timer_start(&timer); await(io_completed() || timer_expired(&timer)); read_data(); } } async_end; } This library is basically a modified version of the idioms found in the Protothreads library by Adam Dunkels, so it's not truly ground bre

Building a Query DSL in C#

I recently built a REST API prototype where one of the endpoints accepted a string representing a filter to apply to a set of results. For instance, for entities with named properties "Foo" and "Bar", a string like "(Foo = 'some string') or (Bar > 99)" would filter out the results where either Bar is less than or equal to 99, or Foo is not "some string". This would translate pretty straightforwardly into a SQL query, but as a masochist I was set on using Google Datastore as the backend, which unfortunately has a limited filtering API : It does not support disjunctions, ie. "OR" clauses. It does not support filtering using inequalities on more than one property. It does not support a not-equal operation. So in this post, I will describe the design which achieves the following goals: A backend-agnostic querying API supporting arbitrary clauses, conjunctions ("AND"), and disjunctions ("OR"). Implemen

Simple, Extensible IoC in C#

I just committed the core of a simple dependency injection container to a standalone assembly, Sasa.IoC . The interface is pretty straightforward: public static class Dependency { // static, type-indexed operations public static T Resolve<T>(); public static void Register<T>(Func<T> create) public static void Register<TInterface, TRegistrant>() where TRegistrant : TInterface, new() // dynamic, runtime type operations public static object Resolve(Type registrant); public static void Register(Type publicInterface, Type registrant, params Type[] dependencies) } If you were ever curious about IoC, the Dependency class is only about 100 lines of code. You can even skip the dynamic operations and it's only ~50 lines of code. The dynamic operations then just use reflection to invoke the typed operations. Dependency uses static generic fields, so resolution is pretty much just a field access + invoking a