入口点不能用“asynchronous”修饰符标记

我从这个链接复制下面的代码。但是当我编译这个代码时,我得到的入口点不能用'async'修饰符标记 。 我怎样才能使这个代码编译?

class Program { static async void 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()); } private static async Task<string> GetWebPageAsync(string url) { // Start an async task. Task<string> getStringTask = (new HttpClient()).GetStringAsync(url); // Await the task. This is what happens: // 1. Execution immediately returns to the calling method, returning a // different task from the task created in the previous statement. // Execution in this method is suspended. // 2. When the task created in the previous statement completes, the // result from the GetStringAsync method is produced by the Await // statement, and execution continues within this method. Debug.WriteLine("In GetWebPageAsync before await"); string webText = await getStringTask; Debug.WriteLine("In GetWebPageAsync after await"); return webText; } // Output: // In GetWebPageAsync before await // In startButton_Click before await // In GetWebPageAsync after await // Characters received: 44306 } 

错误信息是正确的: Main()方法不能是async ,因为当Main()返回时,应用程序通常会结束。

如果你想创build一个使用async的控制台应用程序,一个简单的解决scheme是创build一个async版本的Main()并从真正的Main()同步Wait() Main()

 static void Main() { MainAsync().Wait(); } static async Task MainAsync() { // your async code here } 

这是混合awaitWait()是一个好主意的罕见情况之一,你通常不应该这样做。

更新 : C#7.1支持 Async Main 。

从C#7.1开始, Main方法有4个新的签名,允许将其设置为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); 

你可以用async关键字标记你的Main方法,并在Main里面使用await

 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在Visual Studio 2017 15.3中可用。

链接示例中的代码和您的代码之间的区别在于,您尝试使用async修改器标记Main()方法 – 这是不允许的,而且错误说明了确切的 – Main()方法是“入口点“(这是应用程序启动时执行的方法),并且不允许它是async