Reporting Progress in Async Method

Quite often you would need to provide some kind of progress from your long running asynchronous method, especially if it process multiple activities. Though there might be multiple ways to achieve it, Microsoft provides us with a simple and efficient interface IProgress, which enables us to achieve the result. Let’s hit the code straightaway.

void Main()
{
   InvokeLongRunningMethod();
}

async Task InvokeLongRunningMethod()
{
   Console.WriteLine("Initiating method call");
   var progress = new Progress<string>(ProgressDisplay);
   var result = await LongRunningMethod(progress);
   Console.WriteLine($"Completed executing method with result = {result}");
}


void ProgressDisplay(string update)
{
   Console.WriteLine(update);
}

async Task<bool> LongRunningMethod(IProgress<string> progress)
{

  for(int i=0;i<100;i++)
  {
     await Task.Delay(100);
     if(i%10==0)  progress.Report($"In Progress : {i}%");

  }
  return true;
}

The output would be

Initiating method call
In Progress : 0%
In Progress : 10%
In Progress : 20%
In Progress : 30%
In Progress : 40%
In Progress : 50%
In Progress : 60%
In Progress : 70%
In Progress : 80%
In Progress : 90%
Completed executing method with result = True