steve cook
steve cook

Reputation: 3214

Are c# events handled serially or in parallel?

For example, I have a class that fires an event, and 1000 subscribers to that event. Is a single thread used to fire each subscriber delegate one-by-one? Or does .Net use a thread pool to process some or all of the subscriptions in parallel?

Upvotes: 13

Views: 3480

Answers (2)

Alex des Pelagos
Alex des Pelagos

Reputation: 1465

As Tigran said, event invocation is serial. Even more if one of the subscribers throws an exception at some point the rest of them will not be triggered.

The easiest way to trigger an event in parallel will be

    public event Action Event;

    public void Trigger()
    {
        if (Event != null)
        {
            var delegates = Event.GetInvocationList();
            Parallel.ForEach(delegates, d => d.DynamicInvoke());
        }
    }

This implementation will suffer from same problem in case of an exception.

Upvotes: 11

Tigran
Tigran

Reputation: 62246

As is, event are simple serial invocation. If you want you can run it in async way, but this is an implementation detail.

In short: there is no any built-in parallelization or async of standard .NET events, it's up to you to implement it.

Upvotes: 6

Related Questions