
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Polling an Asynchronous Delegate
|
1025
{
public static int Method1( )
{
Console.WriteLine("Invoked Method1 on Thread {0}",
Thread.CurrentThread.ManagedThreadId );
return (1);
}
}
To run the asynchronous invocation, create an instance of the AsyncAction class and
call the
PollAsyncDelegate method like so:
AsyncAction aa = new AsyncAction( );
aa.PollAsyncDelegate( );
The output for this code is shown next. Note that the Method1 thread ID is different:
Calling BeginInvoke on Thread 9
Starting Polling on Thread 9
Invoked Method1 on Thread 10
.Finished Polling on Thread 9
retVal: 1
Discussion
The delegate, AsyncInvoke, is invoked asynchronously using its BeginInvoke method.
The
BeginInvoke method returns an IAsyncResult object, which allows access to the
result information from an asynchronous operation.
If the delegate accepts a
string and an int, in this order, the BeginInvoke method is
defined as this:
public IAsyncResult BeginInvoke(string s, int i, AsyncCallback callback,
object state)
For this recipe, the method that the delegate will call takes no arguments, and the
callback and state parameters are set to null. The callback parameter could call
back at completion into the code that invoked it, but for this example, it is a no-op.
To poll for the completion of the
method1 delegate, you get the ...