JkriDk
JkriDk

Reputation: 33

C# keep event handling thread alive in CPU friendly way

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:

  1. Code for handling the event that is raised when the RS232 device returns data.
  2. Code for handling Timer events that are raised when the RS232 device does not return data within a predefined time frame.

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

Answers (1)

hannesRSA
hannesRSA

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

Related Questions