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?
-
1Serially, although you can change the event-raising code to parallelize it yourself. (Did you try it before asking the question?)– Jon SkeetCommented Jun 17, 2014 at 6:29
-
Both ways, refer this– Nilay VishwakarmaCommented 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.– KimmaxCommented Jun 17, 2014 at 6:32
2 Answers
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.
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.