
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
1030
|
Chapter 18: Threading and Synchronization
This callback delegate will call the DelegateCallback method on the thread the
method was invoked on when the asynchronous delegate is finished processing.
The following code defines the
AsyncInvoke delegate and the asynchronously invoked
static method
TestAsyncInvoke.Method1:
public delegate int AsyncInvoke( );
public class TestAsyncInvoke
{
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
CallbackAsyncDelegate method like so:
AsyncAction aa2 = new AsyncAction( );
aa2.CallbackAsyncDelegate( );
The output for this code is shown next. Note that the thread ID for Method1 is
different:
Calling BeginInvoke on Thread 9
Invoked Method1 on Thread 10
Getting callback on Thread 10
retVal (Callback): 1
Discussion
The asynchronous delegates in this recipe are created and invoked in the same fash-
ion as the asynchronous delegate in Recipe 18.4. Instead of using the
IsCompleted
property to determine when the asynchronous delegate is finished processing (or the
WaitOne method to block for a specified time while the asynchronous delegate contin-
ues processing), this recipe uses a callback ...