15.4. Polling an Asynchronous Delegate

Problem

While an asynchronous delegate is executing, you need to continuously poll it to see whether it has completed. This ability is useful when you need to monitor the length of time it takes the asynchronous delegate to execute or if you need to monitor other objects in the system in parallel with this asynchronous delegate, possibly to determine which object finishes first, second, third, and so on. It can also be useful when performing a continuous task, such as displaying an indicator to the user that the asynchronous operation is still running.

Solution

Use the IsCompleted property of the IAsyncResult interface to determine when the asynchronous call has completed. The following example shows how this is accomplished:

using System;
using System.Threading;

public class AsyncAction
{
    public void PollAsyncDelegate( )
    {
        // Set up the delegate
        AsyncInvoke method1 = new AsyncInvoke(TestAsyncInvoke.Method1);
        // Define the AsyncCallback delegate.
        AsyncCallback callBack = new AsyncCallback(TestAsyncInvoke.CallBack);
        IAsyncResult asyncResult = method1.BeginInvoke(callBack,method1);

        while (!asyncResult.IsCompleted)
        {
            // give up the CPU for 1 second
            Thread.Sleep(1000);
            Console.Write('.');
        }
        Console.WriteLine("Finished Polling");

        try
        {
            int retVal = method1.EndInvoke(asyncResult);
            Console.WriteLine("retVal: " + retVal);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString( ));
        }
    }
}

The following code defines the AsyncInvoke delegate and the asynchronously ...

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.