Async Main methods in C# 7.1
January 18, 2018 1 Comment
Async methods have the tendency to bubble up to the top of the call chain. Asynchronous repository calls in a large web application are often accompanied by asynchronous methods in the controllers as well.
However, this has until recently posed a problem in Console applications where the “top” function is Main. The Main function, as we all know, must adhere to a small number of rules, one of which being that it must either be void or return an integer in case we care about the exit code. So what could we do if we wanted to call upon an asynchronous method from Main? We couldn’t change its signature unfortunately to make it async so we turned to other ways like calling GetAwaiter().GetResult() on the awaitable method.
C# 7.1 solves this problem by enabling another type of Main method signature:
class Program { static async Task Main(string[] args) { await Task.Run(() => { for (int i = 0; i < 100; i++) { Console.WriteLine($"Counter: {i}"); } }); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } }
That’s a very neat solution and a long-awaited feature.
The only downside is that Visual Studio 2017, at the time of writing this post, doesn’t yet register Main methods with this new signature. It happens that an application has multiple entry points, i.e. multiple Main methods. As long as they adhere to the “old” signature types we can select one of them in the Application properties:
However, async Main methods won’t be listed there:
So in case there are 2 “traditional” Main entry points and 1 asynchronous one then you’ll only be able to select either of the static void/int types as the startup object. If there’s only one Main method and it is asynchronous then it will be auto-selected by Visual Studio as the entry point, otherwise it will be invisible.
View all various C# language feature related posts here.
Good