how to calculate execution time of a async method in c#

ahsant picture ahsant · May 24, 2018 · Viewed 8.4k times · Source

So I have a Async method which does something asynchronously.

private async static void DoSomethingAsync (int i){}

I call it in a loop lets say 50 times.

for (int i = 0; i < 50; i++)
 {
    DoSomethingAsync (i);
 }

At the end of loop I want to calculate total processing time, I used Stopwatch but as you can imagine it gives me wrong time as it gets called as soon as after the loop, it does not wait for the DoSomethingAsync to finish processing.

how to tell Stopwatch to wait for all the 50 instances of DoSomethingAsync() to finish. I have seen this question, but I cant use Task here.

Answer

Mike picture Mike · May 24, 2018

I don't know why you cannot use Task, my guess is that you are calling it within a Main method or something. So i will go out from that.

Like Martin Ullrich said i would change DoSomethingAsync method to return a task:

private async static Task DoSomethingAsync(int i)
{
    ...
}

Then create a new method that does the loop by adding the methods to a List<Task>:

private static async void PerformLoop()
{
    Stopwatch timer = new Stopwatch();
    timer.Start();
    List<Task> l = new List<Task>();
    for (int i = 0; i < 50; i++)
    {
        l.Add(DoSomethingAsync(i));
    }
    await Task.WhenAll(l);
    timer.Stop();

    Console.WriteLine(timer.Elapsed.TotalSeconds);
}

Now from where you did the loop before, in this case the Main method simply add the new method call in there:

static void Main(string[] args)
{
    PerformLoop();

    Console.ReadLine();
}