Tuesday, November 12, 2013

How to invoke an event handlers asynchronously

How to invoke an event or delegate handlers asynchronously

Variant with the Parallel class (TPL).
public void OnMyEvent(String myValue)
{
    var multiCastDelegate = Interlocked.CompareExchange(ref MyEvent, null, null);
    if (multiCastDelegate == null)
    {
        return;
    }

    var handlers = multiCastDelegate.GetInvocationList()
        .Cast<EventHandler<MyEventArgs>>();

    var args = new MyEventArgs(myValue);
    Parallel.ForEach(
        handlers,
        handler => handler(this, args));
} 

Old variant with the Asynchronous delegates (APM).
public void OnMyEventOld(String myValue)
{
    var multiCastDelegate = Interlocked.CompareExchange(ref MyEvent, null, null);
    if (multiCastDelegate == null)
    {
        return;
    }

    var handlers = multiCastDelegate.GetInvocationList()
        .Cast<EventHandler<MyEventArgs>>();
    foreach (var handler in handlers)
    {
        var args = new MyEventArgs(myValue);
        handler.BeginInvoke(
            this,
            args,
            asyncResult =>
                {
                    var asyncDelegate = (EventHandler<MyEventArgs>)((AsyncResult)asyncResult).AsyncDelegate;
                    try
                    {
                        asyncDelegate.EndInvoke(asyncResult);
                    }
                    catch (Exception ex)
                    {
                        ProcessException(ex);
                    }
                },
            null);
    }
}


Aggregating Exceptions
Should event handlers in C# ever raise exceptions?
Thread Safe Event Calls
Release IS NOT Debug: 64bit ...

No comments:

Post a Comment