An entry point cannot be marked with the 'async' modifier
Starting from C# 7.1 there are 4 new signatures for Main
method which allow to make it async
(Source, Source 2, Source 3):
public static Task Main();
public static Task<int> Main();
public static Task Main(string[] args);
public static Task<int> Main(string[] args);
You can mark your Main
method with async
keyword and use await
inside Main
:
static async Task Main(string[] args)
{
Task<string> getWebPageTask = GetWebPageAsync("http://msdn.microsoft.com");
Debug.WriteLine("In startButton_Click before await");
string webText = await getWebPageTask;
Debug.WriteLine("Characters received: " + webText.Length.ToString());
}
C# 7.1 is available in Visual Studio 2017 15.3.
The error message is exactly right: the Main()
method cannot be async
, because when Main()
returns, the application usually ends.
If you want to make a console application that uses async
, a simple solution is to create an async
version of Main()
and synchronously Wait()
on that from the real Main()
:
static void Main()
{
MainAsync().Wait();
}
static async Task MainAsync()
{
// your async code here
}
This is one of the rare cases where mixing await
and Wait()
is a good idea, you shouldn't usually do that.
Update: Async Main is supported in C# 7.1.