O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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); } ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required