Monday, September 7, 2015

Calling Async Call from Main()

This is a small code which shows different ways of calling an async method inside Main

Following is my sample method.

  1. public async Task<int>SampleMethod()
  2.     {
  3.         await Task.Delay(5000);
  4.         int answer = 21 * 2;
  5.         return answer;
  6.     }

 

1. Using  GetAwaiter()

 

  1. static void Main(string[] args)
  2.     {
  3.         SampleMethod().GetAwaiter().OnCompleted(() =>
  4. {
  5.     Console.WriteLine("finished");
  6. });
  7.         Console.ReadKey();
  8.     }

 

2. Using  Wait()

  1. static void Main(string[] args)
  2.     {
  3.         SampleMethod().Wait();
  4.     }

 

Hope this helps,

No comments :

Post a Comment