Async Main methods in C# 7.1

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:

Selecting the Main method startup object in visual studio

However, async Main methods won’t be listed there:

Async main function not selectable in visual studio c sharp 7

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to Async Main methods in C# 7.1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: