CHAPTER 19 MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING
new AsyncCallback(AddComplete), null);
}
// Assume other work is performed here...
while (!isDone)
{
Thread.Sleep(1000);
Console.WriteLine("Working....");
}
Console.ReadLine();
static int Add(int x, int y)
{
Console.WriteLine("Add() invoked on thread {0}.",
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(5000);
return x + y;
}
}
}
static void AddComplete(IAsyncResult itfAR)
{
Console.WriteLine("AddComplete() invoked on thread {0}.",
Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Your addition is complete");
isDone = true;
}
Again, the static AddComplete() method will be invoked by the AsyncCallback delegate when the
Add() method has completed. If you run this program, you can confirm that the secondary thread is the
thread invoking the AddComplete() callback:
***** AsyncCallbackDelegate Example *****
Main() invoked on thread 1.
Add() invoked on thread 3.
Working....
Working....
Working....
Working....
Working....
AddComplete() invoked on thread 3.
Your addition is complete
Like other examples in this chapter, your output might be slightly different. In fact, you might see
one final “Working…” printout occur after the addition is complete. This is just a byproduct of the forced
1-second delay in Main().
707