Free mag vol1 | Page 759

CHAPTER 19  MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING static void Main(string[] args) { ... BinaryOp b = new BinaryOp(Add); // Once the next statement is processed, // the calling thread is now blocked until // BeginInvoke() completes. IAsyncResult iftAR = b.BeginInvoke(10, 10, null, null); // This call takes far less than five seconds! Console.WriteLine("Doing more work in Main()!"); // Now we are waiting again for other thread to complete! int answer = b.EndInvoke(iftAR); ... } Obviously, asynchronous delegates would lose their appeal if the calling thread had the potential of being blocked under various circumstances. To allow the calling thread to discover whether the asynchronously invoked method has completed its work, the IAsyncResult interface provides the IsCompleted property. Using this member, the calling thread is able to determine whether the asynchronous call has indeed completed before calling EndInvoke(). If the method has not completed, IsCompleted returns false, and the calling thread is free to carry on its work. If IsCompleted returns true, the calling thread is able to obtain the result in the “least blocking manner” possible. Ponder the following update to the Main() method: static void Main(string[] args) { ... BinaryOp b = new BinaryOp(Add); IAsyncResult iftAR = b.BeginInvoke(10, 10, null, null); // This message will keep printing until // the Add() method is finished. while(!iftAR.IsCompleted) { Console.WriteLine("Doing more work in Main()!"); Thread.Sleep(1000); } // Now we know the Add() method is complete. int answer = b.EndInvoke(iftAR); ... } Here, you enter a loop that will continue processing the Console.WriteLine() statement until the secondary thread has completed. After this has occurred, you can obtain the result of the Add() method, knowing full well the method has indeed completed. The call to Thread.Sleep(1000) is not necessary for this particular application to function correctly; however, by forcing the primary thread to wait for approximately one second during each iteration, it prevents the same message from printing hundreds of times. Here is the output (your output might differ slightly, based on the speed of your machine and when threads come to life): 704