Free mag vol1 | Page 770

CHAPTER 19  MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING Working with the ThreadStart Delegate To illustrate the process of building a multithreaded application (as well as to demonstrate the usefulness of doing so), assume you have a Console Application (SimpleMultiThreadApp) that allows the end user to choose whether the application will perform its duties using the single primary thread or split its workload using two separate threads of execution. Assuming you have imported the System.Threading namespace, your first step is to define a method to perform the work of the (possible) secondary thread. To keep focused on the mechanics of building multithreaded programs, this method will simply print out a sequence of numbers to the console window, pausing for approximately two seconds with each pass. Here is the full definition of the Printer class: public class Printer { public void PrintNumbers() { // Display Thread info. Console.WriteLine("-> {0} is executing PrintNumbers()", Thread.CurrentThread.Name); } // Print out numbers. Console.Write("Your numbers: "); for(int i = 0; i < 10; i++) { Console.Write("{0}, ", i); Thread.Sleep(2000); } Console.WriteLine(); } Now, within Main(), you will first prompt the user to determine whether one or two threads will be used to perform the application’s work. If the user requests a single thread, you will simply invoke the PrintNumbers() method within the primary thread. However, if the user specifies two threads, you will create a ThreadStart delegate that points to PrintNumbers(), pass this delegate object into the constructor of a new Thread object, and call Start() to inform the CLR this thread is ready for processing. To begin, set a reference to the System.Windows.Forms.dll assembly (and import the System.Windows.Forms namespace) and display a message within Main() using MessageBox.Show() (you’ll see the point of doing so after you run the program). Here is the complete implementation of Main(): static void Main(string[] args) { Console.WriteLine("***** The Amazing Thread App *****\n"); Console.Write("Do you want [1] or [2] threads? "); string threadCount = Console.ReadLine(); // Name the current thread. Thread primaryThread = Thread.CurrentThread; primaryThread.Name = "Primary"; 715