Using async main in .NET Core
Recently, I’ve tried to run a .NET Core console app with an async main method. The main method simply calls an async method using async and await. The program was quite simple and looked like the following sample:
using System;
using System.Threading.Tasks;
namespace AsyncMain
{
class Program
{
static async Task Main(string[] args)
{
var helloWorld = await GetHelloWorldAsync();
Console.WriteLine(helloWorld);
}
static Task<string> GetHelloWorldAsync()
{
return Task.FromResult("Hello Async World");
}
}
}
Trying to build or run this program produces a compiler error
[stef@ws tmp]$ dotnet build
Microsoft (R) Build Engine version 15.7.179.62826 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.
Restore completed in 40.19 ms for /home/stef/tmp/tmp.csproj.
Program.cs(8,22): error CS8107: Feature 'async main' is not available in C# 7.0. Please use language version 7.1 or greater. [/home/stef/tmp/tmp.csproj]
CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point [/home/stef/tmp/tmp.csproj]
Build FAILED.
As the error messages already suggests, the async main - Feature is only available in language version 7.1 or greater.
It turns out, to simply put the right C# language version in the csproj file using the LangVersion tag. Async main methods are supported by the C# compiler since C# 7.1, just set the value to 7.1, or use latest so the compiler accepts all valid language syntax that it can support.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
<LangVersion>latest</LangVersion>
</PropertyGroup>
</Project>
Now, our program will run perfectly with async and await.
$ dotnet run
Hello Async World
Note: When you’re using the C# Extension for Visual Studio Code, in your user settings file set the omnisharp version to latest for using the newest C# Features within Visual Studio Code
{
"omnisharp.path": "latest"
}