【发布时间】:2021-09-19 09:52:38
【问题描述】:
我从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
}
【问题讨论】:
-
你不能用异步标记
Main。 -
@JCL:如何在 main 方法中调用 async/awai 方法
-
您可以在this link 上找到有关 async 和 await 的所有信息。我不确定你的概念是否正确。
-
我知道在 wpf 中它工作正常。但是对于演示,我已经创建了控制台,我想在控制台中进行测试
-
只需从
Main函数中获取你想要异步调用的代码,然后从Main中的代码调用你的函数。
标签: c# async-await c#-5.0