How to call async method in static void Main(string args[])

Posted by

This code is a simple console application written in C# that demonstrates the use of asynchronous programming in a synchronous Main method. Here’s an explanation of the code step by step:

  1. Main Method:
   static void Main(string[] args)
       var helloWorld = GetHelloWorldAsync().GetAwaiter().GetResult();
  • The Main method is the entry point of the console application. It’s marked as static, indicating that it belongs to the class and not to any specific instance.
  • Inside the Main method, we perform the following steps:
    • We call the GetHelloWorldAsync method asynchronously using GetAwaiter().GetResult(). This combination essentially blocks the execution of the Main method until the asynchronous operation in GetHelloWorldAsync is completed.
    • We store the result of the asynchronous operation in the helloWorld variable.
    • Finally, we print the result to the console.
  1. GetHelloWorldAsync Method:
   static Task<string> GetHelloWorldAsync()
       return Task.FromResult("Hello Async World");
  • GetHelloWorldAsync is a static method that returns a Task<string>.
  • Inside this method, we use Task.FromResult to create a completed Task with the result set to the string "Hello Async World". This essentially simulates an asynchronous operation that completes immediately.

In summary, this code demonstrates how to call an asynchronous method (GetHelloWorldAsync) from a synchronous Main method. It does this by using .GetAwaiter().GetResult() to block the Main method until the asynchronous operation is finished.

It’s important to note that while this approach can be useful in some situations, it should be used cautiously, especially in production code. Blocking the Main method like this can lead to deadlocks and decreased application responsiveness if not used carefully. In most cases, it’s recommended to embrace the asynchronous nature of tasks and use await throughout your code instead of blocking the main thread.