
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
498
|
Chapter 9: Delegates, Events, and Anonymous Methods
The code to use this delegate is:
public static void TestComplexSyncDelegate( )
{
SyncDelegateType sdtInstance =
new SyncDelegateType(TestSyncDelegateType.Method1);
int retVal = sdtInstance("Synchronous call");
Console.WriteLine("Sync: " + retVal);
}
The synchronous invocation of the delegate can be converted to asynchronous invo-
cation in the following manner:
public static void TestCallbackAsyncDelegate( )
{
AsyncCallback callBack =
new AsyncCallback(DelegateCallback);
SyncDelegateType sdtInstance =
new SyncDelegateType(TestSyncDelegateType.Method1);
IAsyncResult asyncResult =
sdtInstance.BeginInvoke("Asynchronous call", callBack, null);
Console.WriteLine("WORKING...");
}
// The callback that gets called when TestSyncDelegateType.Method1
// is finished processing
private static void DelegateCallback(IAsyncResult iResult)
{
AsyncResult result = (AsyncResult)iResult;
SyncDelegateType sdtInstance =
(SyncDelegateType)result.AsyncDelegate;
int retVal = sdtInstance.EndInvoke(result);
Console.WriteLine("retVal (Callback): " + retVal);
}
Discussion
Converting the invocation of a delegate from being synchronous to asynchronous is
not an overly complicated procedure. You need to add calls to both
BeginInvoke and
EndInvoke on the delegate ...