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

15,439

Solution 1

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.

Solution 2

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.

Solution 3

My guess is that you want to simply go away from triggering the action by raising an event and calling the method directly.

AFAIK events are going to be async and I am not aware of any "easy" ways of changing that.

Solution 4

Turns out there's another answer. You can just add the following attribute to the method.

[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)]
Share:
15,439
rc1
Author by

rc1

Updated on June 04, 2022

Comments

  • rc1
    rc1 almost 2 years

    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?

  • rc1
    rc1 about 15 years
    Thanks Eric. I think I'll do that.