How I called an asynchronous method from a loop

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

  • How to call an async method from a console app main method
  • How to deploy a .NET Core console application to Azure, WebJob
  • .NET Core application, where is my EXE, how to publish
  • Create a VNET and access an Azure VM hosted within it from an App Services Web App
  • Create and deploy an ASP.NET Core Web API to Azure Windows

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.  You should use this only for testing scenarios, calling the .Wait() or .Result is the same, and likely worse than calling a synchronous method.  When coding ASYNC applications use the principle “ASYNC all the way up”, meaning don’t mix and match.