7.4. Converting a Synchronous Delegate to an Asynchronous Delegate
Problem
You have determined that one or more delegates invoked synchronously within your application are taking a long time to execute. This delay is making the user interface less responsive to the user. These delegates should be converted to asynchronous delegates.
Solution
A typical synchronous delegate is created in the following manner:
using System; // The delegate declaration public delegate void SyncInvoke( ); // The class and method that is invoked through the SyncInvoke delegate public class TestSyncInvoke { public static void Method1( ) { Console.WriteLine("Invoked Method1"); } }
The code to use this delegate is:
public class DelegateUtilities { public void TestSimpleSyncDelegate( ) { SyncInvoke SI = new SyncInvoke(TestSyncInvoke.Method1); SI( ); } }
This delegate can be called asynchronously on a thread obtained from the thread pool by modifying the code as follows:
public class DelegateUtilities { public void TestSimpleAsyncDelegate( ) { AsyncCallback CB = new AsyncCallback(DelegateCallback); SyncInvoke ASI = new SyncInvoke(TestSyncInvoke.Method1); IAsyncResult AR = ASI.BeginInvoke(CB, null); } // The callback that gets called when Method1 is finished processing private static void DelegateCallback(IAsyncResult iresult) { AsyncResult result = (AsyncResult)iresult; AsyncInvoke ASI = (AsyncInvoke)result.AsyncDelegate; int retVal = ASI.EndInvoke(result); Console.WriteLine("retVal (Callback): " + retVal); } ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.