我从this链接复制下面的代码。但是当我编译此代码时,我得到的入口点无法用'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
}
答案 0 :(得分:72)
错误消息完全正确:Main()
方法不能是async
,因为当Main()
返回时,应用程序通常会结束。
如果您想创建一个使用async
的控制台应用程序,一个简单的解决方案就是创建一个async
版本的Main()
并同步Wait()
Main()
:
static void Main()
{
MainAsync().Wait();
}
static async Task MainAsync()
{
// your async code here
}
这是混合await
和Wait()
是个好主意的极少数情况之一,你通常不应该这样做。
答案 1 :(得分:11)
从C#7.1开始,Main
方法有4个新签名,可以使其async
(Source,Source 2,Source 3):< / p>
public static Task Main();
public static Task<int> Main();
public static Task Main(string[] args);
public static Task<int> Main(string[] args);
您可以使用Main
关键字标记async
方法,并在await
内使用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());
}
Visual Studio 2017 15.3中提供了C#7.1。
答案 2 :(得分:1)
链接示例中的代码与您的代码之间的区别在于,您尝试使用Main()
修饰符标记async
方法 - 这是不允许的,并且错误说明了 - Main()
方法是应用程序的“入口点”(它是应用程序启动时执行的方法),并且不允许async
。
答案 3 :(得分:0)
将您的异步代码包裹在MainAsync()
中 - 这是一个异步功能
然后拨打MainAsync().GetAwaiter().GetResult();
答案 4 :(得分:0)
static async Task Main(string[] args)
{
var response = await SomeAsyncFunc();
Console.WriteLine("Async response", response);
}
不带“ await”关键字的“或”。
static void Main(string[] args)
{
var response = SomeAsyncFunc().GetAwaiter().GetResult();
Console.WriteLine("Async response", response);
}