Free mag vol1 | Page 758

CHAPTER 19  MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING Invoking a Method Asynchronously To instruct the BinaryOp delegate to invoke Add() asynchronously, you will modify the logic in the previous project (feel free to add code to the existing project; however, in your lab downloads, you will find a new Console Application named AsyncDelegate). Update the previous Main() method as follows: static void Main(string[] args) { Console.WriteLine("***** Async Delegate Invocation *****"); // Print out the ID of the executing thread. Console.WriteLine("Main() invoked on thread {0}.", Thread.CurrentThread.ManagedThreadId); // Invoke Add() on a secondary thread. BinaryOp b = new BinaryOp(Add); IAsyncResult iftAR = b.BeginInvoke(10, 10, null, null); // Do other work on primary thread... Console.WriteLine("Doing more work in Main()!"); } // Obtain the result of the Add() // method when ready. int answer = b.EndInvoke(iftAR); Console.WriteLine("10 + 10 is {0}.", answer); Console.ReadLine(); If you run this application, you will find that two unique thread IDs are displayed, given that there are in fact multiple threads working within the current AppDomain: ***** Async Delegate Invocation ***** Main() invoked on thread 1. Doing more work in Main()! Add() invoked on thread 3. 10 + 10 is 20. In addition to the unique ID values, you will also notice upon running the application that the Doing more work in Main()! message displays immediately, while the secondary thread is occupied attending to its business. Synchronizing the Calling Thread If you think carefully about the current implementation of Main(), you might realize that the timespan between calling BeginInvoke() and EndInvoke() is clearly less than five seconds. Therefore, once Doing more work in Main()! prints to the console, the calling thread is now blocked and waiting for the secondary thread to complete before being able to obtain the result of the Add() method. Therefore, you are effectively making yet another synchronous call. 703