Simple Progress reporting
suggest changeIProgress<T> can be used to report progress of some procedure to another procedure. This example shows how you can create a basic method that reports its progress.
using System;
using System.Threading;
public static class Program
{
public static void Main()
{
using (var completed = new CountdownEvent(10))
{
IProgress<int> progress = new Progress<int>(step =>
{
Console.WriteLine("Running Step: {0}", step);
completed.Signal();
});
LongJob(progress);
completed.Wait();
}
}
private static void LongJob(IProgress<int> progress)
{
const int max = 10;
for (var step = 0; step < max; step++)
{
progress.Report(step);
}
}
}
Running Step: 0
Running Step: 3
Running Step: 4
Running Step: 5
Running Step: 6
Running Step: 7
Running Step: 8
Running Step: 9
Running Step: 2
Running Step: 1
When this code runs, the numbers may be printed out of order. Progress<T> posts each Report call asynchronously, so it is a poor fit when progress must be observed in order. On a thread with no SynchronizationContext, those callbacks run on the thread pool.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents