How I called an asynchronous method from a loop


This article has been moved to its new home here:  https://benperk.github.io/msdn/2017/2017-03-how-i-called-an-asynchronous-method-from-a-loop.html

Check out some of my other articles I wrote in reagrds to ASP.NET Core and .Net Core

I wrote this article here where I showed "How to call an async method from a console app main method", but I needed also to call it numerous times.  Here is the code snippet that illustrates how I did that.

public static void Main(string[] args)
{
 try
 {
  int i = 0;
  while (i < 10)
  {
   Task.Run(() => callWebApi()).Wait();
   i++;
  }
 }
 catch (Exception ex)
 {
  WriteLine($"[MAIN] There was an exception: {ex.ToString()}");
 }
}

Simply, I used the Wait() method of the Task.

Comments (2)
  1. kae says:

    If you want concurrent/asynchronous execution you should write

    int i = 0;
    while (i callWebApi()).Wait();
    i++;
    }

    as

    Task.WaitAll(Enumerable.Range(0, 10).Select(i => callWebApi()).ToArray());

    if you wouldn’t mind basically syncronous execution then

    int i = 0;
    while (i < 10)
    {
    callWebApi().Wait();
    i++;
    }

    1. @Kae, I appreciate very much your comments. I like the pattern you provide.

Comments are closed.

Skip to main content