Search This Blog

Tuesday, January 26, 2010

C# Threading - Wait Handles

Wait handles are suitable for signaling a waiting worker thread to begin a task from where it is paused. This is obviously done cross threads(also capable of cross process), means that we can signal from main thread to the worker thread to start its execution from the place where the worked thread paused its execution.

This is done through a construct called as "WaitHandle". WaitHandle is implemented via class named "EventWaitHanlde".

The syntax for creating EventWaitHanlde is the following:
EventWaitHanlde ewh = new EventWaitHanlde(false, EventResetMode.Auto);

The above parameters for the EventWaitHandle are the ones that would be used in most of the cases. The first parameter "false" states not to start the execution atonce but wait for the signal. EventResetMode.Auto means that only one request will be executed for one signal.

class clsTestWaitHandle
{
static EventWaitHandle ewh = new EventWaitHandle(false,EventResetMode.Auto);
static void Main()
{
new Thread (Job).Start();
Console.WriteLine ("Main Thread executing...");
Console.WriteLine ("Main Thread now going to notify the worker thread...");
wh.Set(); // wake up the worker thread
}
static void Job()
{
Console.WriteLine ("Worker Thread Started...");
Console.WriteLine ("Worker Thread will start waiting now...");
ewh.WaitOne(); // Wait for the notification
Console.WriteLine ("Worker thread Notified and resumes execution");
}
}

OUTPUT:
Worker Thread Started...
Worker Thread will start waiting now...
Main Thread executing...
Main Thread now going to notify the worker thread...
Worker thread Notified and resumes execution

The WaitHanlde as said earlier can be cross process also. This is done by giving name to the EventWaitHandle object. If the name is already in use on the computer by some other EventWaitHandle object, reference to the same underlying EventWaitHandle will be created, otherwise the operating system creates a new one.

Here's an example:
EventWaitHandle ewh = new EventWaitHandle (false, EventResetMode.Auto,
"OrganizationName.ProjectName");
If two applications each ran this code, they would be able to signal each other: the wait handle would work across all threads in both processes.

No comments:

Post a Comment