Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of having async Main?

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?

like image 697
Exerion Avatar asked Sep 14 '17 12:09

Exerion


People also ask

What is the benefit of using async?

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.

What is the point of async?

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.

Can main be async?

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.

Is async necessary?

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.


1 Answers

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.

like image 149
David Arno Avatar answered Oct 12 '22 08:10

David Arno