Oytun Yilmaz Oytun Yilmaz - 1 month ago 22
C# Question

Event handling in multi thread c# winforms

I develop multi-thread application that event handling done in threads. When event raises in UI thread creates a thread that executes business logic and terminates. However, if business logic code in worker thread causes another event; thread Invokes control on main UI thread and moves on its execution. At the same time, UI thread creates new thread for new event handling. Both these thread executes in a parallel way.

What I want is that if thread causes a new event; wait for new event completition and moves on their task. Events should be handled in order.

My task is actually a part of large framework. Briefly application binds control events to target codes by using reflection api.

UI Thread process code below When event is captured.

Thread workerThread = new Thread(() => executeCommandTargetAsync( ..some parameters.. ));
workerThread.Start();


Worker thread communicates with UI Thread by using Control's InvokeRequired flag and Invoke Method.
Purpose of handling of events in other threads instead of UI Thread prevent to freeze UI because of long event operation such as changing datasource of combo box from database.

Answer

try to use the class "AutoResetEvent" :

 AutoResetEvent resetEvent = new AutoResetEvent(false);

 resetEvent.WaitOne();


 //pass the resetEvent object to thread 2, and when you want to continue processing the thread 1 you use the method resetEvent.Set();