.NET Framework Using Progress and IProgress Simple Progress reporting

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

IProgress<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.

void Main()
{
    IProgress<int> p = new Progress<int>(progress =>
    {
        Console.WriteLine("Running Step: {0}", progress);
    });
    LongJob(p);
}

public void LongJob(IProgress<int> progress)
{
    var max = 10;
    for (int i = 0; i < max; i++)
    {
        progress.Report(i);
    }
}

Output:

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

Note that when you this code runs, you may see numbers be output out of order. This is because the IProgress<T>.Report() method is run asynchronously, and is therefore not as suitable for situations where the progress must be reported in order.



Got any .NET Framework Question?