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 ...

Comments

Popular posts from this blog

Convention over Git = CoG

jQuery Deferred Object method chain or a Syntactic Sugar

Ctrl+Shift+Right arrow doesn't work in Visual Studio 2019