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,

Comments

Popular posts from this blog

Responsive Web Design

Affine Cipher in C#

Contract First Development in WCF 4.5