As we know, C#7 allows to make Main() function asynchronous.
What advantages it gives? For what purpose may you use async Main instead of a normal one?
with async / await , you write less code and your code will be more maintainable than using the previous asynchronous programming methods such as using plain tasks. async / await is the newer replacement to BackgroundWorker , which has been used on windows forms desktop applications.
Note: The purpose of async / await is to simplify the syntax necessary to consume promise-based APIs. The behavior of async / await is similar to combining generators and promises. Async functions always return a promise.
An async Main method enables you to use await in your Main method. Before C# 7.1, when you want to call the async method from the Main method, you need to add some boilerplate code, as shown below. Now in C# 7.1, the syntax is simpler and easy to use only using the async main.
Asynchronous loops are necessary when there is a large number of iterations involved or when the operations within the loop are complex. But for simple tasks like iterating through a small array, there is no reason to overcomplicate things by using a complex recursive function.
It's actually C# 7.1 that introduces async main.
The purpose of it is for situations where you Main
method calls one or more async methods directly. Prior to C# 7.1, you had to introduce a degree of ceremony to that main method, such as having to invoke those async methods via SomeAsyncMethod().GetAwaiter().GetResult()
.
By being able to mark Main
as async
simplifies that ceremony, eg:
static void Main(string[] args) => MainAsync(args).GetAwaiter().GetResult();
static async Task MainAsync(string[] args)
{
await ...
}
becomes:
static async Task Main(string[] args)
{
await ...
}
For a good write-up on using this feature, see C# 7 Series, Part 2: Async Main.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With