Reputation: 33
I would like to run 10 threads in parallel. Each thread contains code that handles serial port communication (Using the 'SerialPort' class). Some of the features are:
As you can see each thread handles some asynchronous events initialized and started from the thread itself. So the thread needs to keep itself alive until all events have been raised and processed. Based on the received data from the RS232 device the thread knows when the work is done and the thread can kill itself.
Now my question: I would like to avoid using an infinite loop to keep the thread alive to avoid using a lot of CPU resources on nothing. Any idea how to do this and also avoiding that the thread blocks/stops itself?.
Upvotes: 3
Views: 1542
Reputation: 76
The most efficient way to keep the 10 threads idle based on a condition is to use a WaitHandle.
The ManualResetEvent class allows you to simply signal when you want to continue execution. You can signal multiple threads with the same handle.
class Work
{
public static void WorkMethod(object stateInfo)
{
Console.WriteLine("Work starting.");
((ManualResetEvent)stateInfo).WaitOne();
Console.WriteLine("Work ending.");
}
}
// Example:
ManualResetEvent manualEvent = new ManualResetEvent(false);
Thread newThread = new Thread(Work.WorkMethod);
newThread.Start(manualEvent);
// This will terminate all threads that are waiting on this handle:
manualEvent.Set();
Upvotes: 4