CHAPTER 19 MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING
// Make an AddParams object to pass to the secondary thread.
AddParams ap = new AddParams(10, 10);
Thread t = new Thread(new ParameterizedThreadStart(Add));
t.Start(ap);
// Force a wait to let other thread finish.
Thread.Sleep(5);
}
Console.ReadLine();
The AutoResetEvent Class
In these first few examples, you have made use of a few crude ways to inform the primary thread to wait
until the secondary thread has completed. During your examination of asynchronous delegates you
used a simple bool variable as a toggle; however, this is not a recommended solution, as both threads
can access the same point of data, and this can lead to data corruption. A safer, but still undesirable
alternative is to call Thread.Sleep() for a fixed amount of time. The problem here is that you don’t want
to wait longer than necessary.
One simple, and thread-safe way to force a thread to wait until another is completed is to use the
AutoResetEvent class. In the thread that needs to wait (such as a Main() method), create an instance of
this class, and pass in false to the constructor in order to signify you have not yet been notified. Then, at
the point at which you are willing to wait, call the WaitOne() method. Here is the update to Program class,
which will do this very thing using a static-level AutoResetEvent member variable:
class Program
{
private static AutoResetEvent waitHandle = new AutoResetEvent(false);
static void Main(string[] args)
{
Console.WriteLine("***** Adding with Thread objects *****");
Console.WriteLine("ID of thread in Main(): {0}",
Thread.CurrentThread.ManagedThreadId);
AddParams ap = new AddParams(10, 10);
Thread t = new Thread(new ParameterizedThreadStart(Add));
t.Start(ap);
// Wait here until you are notified!
waitHandle.WaitOne();
Console.WriteLine("Other thread is done!");
}
...
}
Console.ReadLine();
When the other thread is completed with its workload, it will call the Set() method on the same
instance of the AutoResetEvent type.
718