44 c# async-await c#-5.0
我从这个 链接复制下面的代码.但是当我编译这段代码时,我得到的入口点不能用'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
}
Run Code Online (Sandbox Code Playgroud)
svi*_*ick 76
错误消息是完全正确的:Main()方法不能async,因为当Main()返回时,应用程序通常结束.
如果你想创建一个使用的控制台应用程序async,一个简单的解决方案是创建一个真实的async版本Main()并同步:Wait()Main()
static void Main()
{
MainAsync().Wait();
}
static async Task MainAsync()
{
// your async code here
}
Run Code Online (Sandbox Code Playgroud)
这是其中混合少见的情况await和Wait()是一个好主意,你通常不应这样做.
Rom*_*och 11
从C#7.1开始,有4个新的签名Main方法允许它async(源,源2,源3):
public static Task Main();
public static Task<int> Main();
public static Task Main(string[] args);
public static Task<int> Main(string[] args);
Run Code Online (Sandbox Code Playgroud)
您可以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());
}
Run Code Online (Sandbox Code Playgroud)
Visual Studio 2017 15.3中提供了C#7.1.
| 归档时间: |
|
| 查看次数: |
10176 次 |
| 最近记录: |