Calling async method in C# main method

I have encountered this situation recently when I had to call a async method from the main method of my program. This async method was used on other places as well in the project so I can’t change it so only option I had was to do something while calling it in my main method.

There are two ways of doing this:

For C# versions older then 7.1

static void Main(string[] args)
{
    MyClass obj = new MyClass();
    obj.Method().Wait();
}

For C# versions older then 7.1 we can simply use wait extension method.

For C# version 7.1 and later

static async Task Main(string[] args)
{
    MyClass obj = new MyClass();
    await obj.Method();
}

If you are using C# version 7.1 or later then you can also change your main method to an async main method and then you will be able to call the async method in it with await keyword.

For C# version 7.1 and newer you can also use older way of calling wait method.