Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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); } ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata