
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
1024
|
Chapter 18: Threading and Synchronization
Solution
Use the IsCompleted property of the IAsyncResult interface to determine when the
asynchronous call has completed. Note that the
BeginInvoke method call on the dele-
gate passes
null for the callback setup parameters. Example 18-3 shows how this is
accomplished.
The following code defines the
AsyncInvoke delegate and the asynchronously invoked
static method
TestAsyncInvoke.Method1:
public delegate int AsyncInvoke( );
public class TestAsyncInvoke
Example 18-3. Polling an asynchronous delegate
using System;
using System.Threading;
public class AsyncAction
{
public void PollAsyncDelegate( )
{
// Set up the delegate.
AsyncInvoke method1 = TestAsyncInvoke.Method1;
// Since we are not using a callback here, we pass null for the
// callback and null for the object data for the callback.
Console.WriteLine("Calling BeginInvoke on Thread {0}",
Thread.CurrentThread.ManagedThreadId);
IAsyncResult asyncResult = method1.BeginInvoke(null, null);
Console.WriteLine("Starting Polling on Thread {0}",
Thread.CurrentThread.ManagedThreadId);
while (!asyncResult.IsCompleted)
{
// Give up the CPU for 1 second.
Thread.Sleep(1000);
Console.Write('.');
}
Console.WriteLine("Finished Polling on Thread {0}",
Thread.CurrentThread.ManagedThreadId);
try
{
int retVal ...