13

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?

3
  • 1
    Serially, although you can change the event-raising code to parallelize it yourself. (Did you try it before asking the question?)
    – Jon Skeet
    Commented Jun 17, 2014 at 6:29
  • Both ways, refer this Commented Jun 17, 2014 at 6:31
  • Why don't you try it yourself? Subcribe 1000 times and save the time the method gets executed. Good question through.
    – Kimmax
    Commented Jun 17, 2014 at 6:32

2 Answers 2

11

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.

6

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.