Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .NET 3.5 : How to invoke an event handler and wait for it to complete

I have a class containing a worker thread which receives data from a queue in a loop.

Another part of the app sinks an event from this class, which the class raises for each queue item.

These events are fired asynchronously, so at busy times the other part of the app can be processing several events at once.

This should be fine but we've discovered a scenario where this can cause problems.

We need a quick solution while the main issue gets addressed. Does the framework provide a simple way I can force the worker thread to wait while each event gets processed (so they are processed sequentially)? If not, what's the easiest way to implement this?

like image 897
rc1 Avatar asked Jan 24 '23 19:01

rc1


2 Answers

A simple answer would be to lock() on a single object in the event handler. All of the theads would wait to get the lock.

like image 96
eduesing Avatar answered Jan 30 '23 06:01

eduesing


The ManualResetEvent class might help you here, unless I'm not understanding your question. You can use it to block the firing of the next event until the last one completes.

like image 42
lc. Avatar answered Jan 30 '23 08:01

lc.