Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are c# events handled serially or in parallel?

Tags:

c#

.net

events

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?

like image 493
steve cook Avatar asked Jun 17 '14 06:06

steve cook


People also ask

Is C+ Same as C?

C++ was developed by Bjarne Stroustrup in 1979. C does no support polymorphism, encapsulation, and inheritance which means that C does not support object oriented programming. C++ supports polymorphism, encapsulation, and inheritance because it is an object oriented programming language. C is (mostly) a subset of C++.

What does %c mean in C programming?

While it's an integer, the %c interprets its numeric value as a character value for display. For instance for the character a : If you used %d you'd get an integer, e.g., 97, the internal representation of the character a. vs. using %c to display the character ' a ' itself (if using ASCII)

Are C and C# same?

C language supports procedural programming. Whereas C# supports object oriented programming.

Is there a C+?

C+ is a slightly above average grade on an assignment (usually within an educational context)... There is much debate on this topic... Low and High level languages: 1.


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.

like image 187
Alex des Pelagos Avatar answered Nov 09 '22 04:11

Alex des Pelagos


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.

like image 21
Tigran Avatar answered Nov 09 '22 04:11

Tigran