Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In .NET, what thread will Events be handled in?

I have attempted to implement a producer/consumer pattern in c#. I have a consumer thread that monitors a shared queue, and a producer thread that places items onto the shared queue. The producer thread is subscribed to receive data...that is, it has an event handler, and just sits around and waits for an OnData event to fire (the data is being sent from a 3rd party api). When it gets the data, it sticks it on the queue so the consumer can handle it.

When the OnData event does fire in the producer, I had expected it to be handled by my producer thread. But that doesn't seem to be what is happening. The OnData event seems as if it's being handled on a new thread instead! Is this how .net always works...events are handled on their own thread? Can I control what thread will handle events when they're raised? What if hundreds of events are raised near-simultaneously...would each have its own thread?

like image 842
Ben Avatar asked Mar 17 '10 02:03

Ben


People also ask

How are events handled in a .NET environment?

Event Handling Using Controls All ASP.NET controls are implemented as classes, and they have events which are fired when a user performs a certain action on them. For example, when a user clicks a button the 'Click' event is generated. For handling events, there are in-built attributes and event handlers.

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.

How does C# handle events?

In C#, an event is connected to its handler by an event delegate. To raise an event and respond to the event, the two necessary elements are the delegate that links the event to its handler method and the class that holds event data.

Are events Async C#?

Yes, they are synchronous.


1 Answers

After re-reading the question, I think I understand the problem now. You've basically got something like this:

class Producer {     public Producer(ExternalSource src)     {         src.OnData += externalSource_OnData;     }      private void externalSource_OnData(object sender, ExternalSourceDataEventArgs e)     {         // put e.Data onto the queue     } } 

And then you've got a consumer thread that pulls stuff off that queue. The problem is that the OnData event is fired by your ExternalSource object - on whatever thread it happens to be running on.

C# events are basically just an easy-to-use collection of delegates and "firing" an event just causes the runtime to loop through all of the delegates and fire them one at a time.

So your OnData event handler is getting called on whatever thread the ExternalSource is running on.

like image 186
Dean Harding Avatar answered Oct 29 '22 16:10

Dean Harding