CHAPTER 19 MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING
// Display Thread info.
Console.WriteLine("-> {0} is executing Main()",
Thread.CurrentThread.Name);
// Make worker class.
Printer p = new Printer();
switch(threadCount)
{
case "2":
// Now make the thread.
Thread backgroundThread =
new Thread(new ThreadStart(p.PrintNumbers));
backgroundThread.Name = "Secondary";
backgroundThread.Start();
break;
case "1":
p.PrintNumbers();
break;
default:
Console.WriteLine("I don't know what you want...you get 1 thread.");
goto case "1";
}
}
// Do some additional work.
MessageBox.Show("I'm busy!", "Work on main thread...");
Console.ReadLine();
Now, if you run this program with a single thread, you will find that the final message box will not
display the message until the entire sequence of numbers has printed to the console. As you are
explicitly pausing for approximately two seconds after each number is printed, this will result in a lessthan-stellar end-user experience. However, if you select two threads, the message box displays instantly,
given that a unique Thread object is responsible for printing out the numbers to the console (see
Figure 19-2).
Figure 19-2. Multithreaded applications provide results in more responsive applications
716