X

Async Main in C# 7

Csharp-MS-Dotnet

In C#7 there is an enhancement in the main method Async Main in C# that will allow you to await in your main method. Let me show you an example of how it was in C#6 and then how it has changed in C#7.

You will remember this most likely

static int Main()
{
    return SomeAsyncCall().GetAwaiter().GetResult();
}

One will need to get the Awaiter and then GetResult in order for it to work. But now in C#7 you can write it like below.

static async Task Main()
{
    Console.WriteLine("Helllo and delay");
    await Task.Delay(2000);   
    return await SomeAsynCall();
}

And to add cherry to the icing, if you have a method that doesn’t return a value you can also just return Task.

static async Task Main()
{
    Console.WriteLine("Helllo and delay");
    await Task.Delay(2000);   
    await SomeAsynCall();
}

Summary

The above code shows the ease that C#7 provides with its main method an great improvement from C#6 I would say, hope that helps you in learning C#.

Categories: .NET C#
Tags: csharpdotnet
Taswar Bhatti:
Related Post