thalm thalm - 2 months ago 13
C# Question

Can you think of an event pattern with synchronization context in .NET?

The main problem is, that raising an event from one thread can invoke delegates which should only invoked in a certain thread context. After doing some research on this problem i thought, maybe its possible to pass some kind of synchronization context along with each subscription to an event:

SomeClass.SmartSyncEvent += (myDelegate, someReferenceToAThread);


and then raise the event and it somehow does:

foreach(subscriber)
{
someReferenceToAThread.Invoke(myDelegate);
}


This is super pseudo code, but maybe someone has already done things like this, or knows of any .NET classes which can set up such a pattern.
thanks!

Answer

The best way to do this is pass SomeClass a synchronization context via ISynchronizeInvoke.

public class SomeClass
{
    public event EventHandler SmartSyncEvent;

    public ISynchronizeInvoke SynchronizingObject { get; set; }

    public void RaiseSmartSyncEvent()
    {
        if (SynchronizingObject != null)
        {
            SynchronizingObject.Invoke(
              (Action)(()=>
              {
                  SmartSyncEvent();
              }), null);
        }
        else
        {
            SmartSyncEvent();
        }
    }
}

This pattern is similar to the way System.Timers.Timer is implemented. The problem with it is that every subscriber will be marshaled onto the same synchronizing object. It does not appear that this is what you want though.

Fortunately delegates store the class instance upon which the method should be invoke via the Target property. We can exploit this by extracting it before we invoke the delegate and using it as the synchronizing object assuming of course that it is a ISynchronizeInvoke itself. We could actually enforce that by using custom add and remove event accessors.

public class SomeClass
{
    private EventHandler _SmartSyncEvent;

    public event EventHandler SmartSyncEvent
    {
        add
        {
            if (!(value.Target is ISynchronizeInvoke))
            {
                throw new ArgumentException();
            }
            _SmartSyncEvent = (EventHandler)Delegate.Combine(_SmartSyncEvent, value);
        }
        remove
        {
            _SmartSyncEvent = (EventHandler)Delegate.Remove(_SmartSyncEvent, value);
        }
    }

    public void RaiseMyEvent()
    {
        foreach (EventHandler handler in _SmartSyncEvent.GetInvocationList())
        {
            var capture = handler;
            var synchronizingObject = (ISynchronizeInvoke)handler.Target;
            synchronizingObject.Invoke(
                (Action)(() =>
                {
                    capture(this, new EventArgs());
                }), null);
        }
    }
}

This is a lot better in that each subscriber can be marshaled independently of the others. The problem with it is that the handlers must be instance methods that reside in an ISynchronizeInvoke class. Also, Delegate.Target is null for static methods. This is why I enforce that constraint with the custom add accessor.


You could make it execute the handlers synchronously if Delegate.Target were null or otherwise could not be casted into a useful synchronizing object. There are a lot of variations on this theme.

In WPF you could code for DispatcherObject instead of ISynchronizeInvoke.

Comments