Home > C# > Async operations and progress updates

Async operations and progress updates

04/07/2013

In the last post we have seen how to use the IProgress interface to receive notification about the progress of an async operation. But what about if we’re developing an async method and we want to provide these updates to the caller?

The IProgress interface defines only a method, Report, that is used to report progress updates. It takes as argument an instance of the generic type that represents the updated progress. So, using it to notify updates is straightforward:

public Task LongRunningTask(int input, IProgress<int> progress)
{
    return Task.Run(async () =>
        {
            for (int i = 0; i < input; i++)
            {
                await Task.Delay(1000);

                // Report progress updates.
                progress.Report(i);
            }
        });
}

In this example we simulate a long running task in which, during each iteration, we wait for 1 second. Then, on line 10, we call the Report method using the index of the current iteration. This value is passed to the caller that has defined the IProgress implementation:

Progress<int> progress = new Progress<int>((p) =>
{
    Debug.WriteLine("Current progress: " + p);
});

await LongRunningTask(10, progress);

We’re using a simple integer value, but we can for example create a class that holds more information about the progress updates.

About these ads
Categories: C#
Comments are closed.
Follow

Get every new post delivered to your Inbox.

Join 32 other followers

%d bloggers like this: