Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Threads subscribing same event

Tags:

c#

events

What will happen when 10 threads will subscribe to the same event and the event fires? Which thread will pick it up?

like image 263
koumides Avatar asked Aug 13 '10 19:08

koumides


People also ask

What will happen if multiple threads accessing the same resource?

Multiple threads accessing shared data simultaneously may lead to a timing dependent error known as data race condition. Data races may be hidden in the code without interfering or harming the program execution until the moment when threads are scheduled in a scenario (the condition) that break the program execution.

Can multiple threads run simultaneously?

In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run concurrently on a separate processor, resulting in parallel execution, which is true simultaneous execution.

Do events run on separate threads?

Answers. 1) No. The event handlers are run off the timer tick event as well as the swapping of thread execution.

Can multiple threads read the same value?

Even though the variable is not currently being written to, previous writes to the variable may not yet be visible to all threads. This means two threads can read the same value and get different results creating a race condition.


2 Answers

Thread's don't subscribe to events, objects do. When an event fires, all of the registered handlers execute on the same thread (the one that raised the event). There's no built-in facility for events to fire on multiple threads.

A handler can choose to forward the event information to a separate thread, if desired, but that's not part of the built-in mechanism of event dispatch.

like image 136
LBushkin Avatar answered Sep 20 '22 18:09

LBushkin


If by "event" you mean a Win32 synchronization Event (which is how I read the question) then it depends on how the EventWaitHandle is created. If its manual reset, the event will signal all threads and all will execute. If its auto reset, a single thread will be signalled and executed. Any of your 10 threads waiting on the event could be chosen.

like image 25
ScottTx Avatar answered Sep 20 '22 18:09

ScottTx