0

I am wondering if the following methods in the Main method implement async/await modifier correctly as to imposing the asynchronous programming in my C# .NET Core console application.

Main method:

static void Main(string[] args)
{
  //...

  MyTask_1_RunAsync(dbConnectionString).Wait();
  MyTask_2_RunAsync(dbConnectionString).Wait();  

  //...
}

Other methods:

static async Task MyTask_1_RunAsync(string dbConnectionString)
{
   //....

   var content = new StringContent(paramObj, Encoding.UTF8, "application/json");
   HttpResponseMessage response = await client.PostAsync(client.BaseAddress, content);
   if (response.IsSuccessStatusCode)
    {
        string jsonString = await response.Content.ReadAsStringAsync();
    }

   //...
}

static async Task MyTask_2_RunAsync(string dbConnectionString)
{
   //....

   var content = new StringContent(paramObj, Encoding.UTF8, "application/json");
   HttpResponseMessage response = await client.PostAsync(client.BaseAddress, content);
   if (response.IsSuccessStatusCode)
    {
        string jsonString = await response.Content.ReadAsStringAsync();
    }

   //...
}
Salahuddin Ahmed
  • 4,854
  • 4
  • 14
  • 35
  • 3
    Use `async Task Main()` instead of calling `.Wait()` on every async method. – Panagiotis Kanavos Aug 08 '21 at 09:23
  • It depends on what you expect to have happen. This code isn't obviously wrong, but may not do what you intend it to do. – dialer Aug 08 '21 at 09:24
  • 4
    `async Task Main` was introduced in C# 7.1 but even with older versions it's a lot better to put all the code into a separate `async` method that's called with `TheAsyncMain().GetAwaiter().GetResult()`. At the very least, you'll get the actual exception in case of problems instead of an `AggregageException` wrapping the actual exception. – Panagiotis Kanavos Aug 08 '21 at 09:30

0 Answers0