Tuesday, July 09, 2013

Async operations and progress updates

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


QR: Inline image 1