Tro*_*yvs 2 c# program-entry-point asynchronous task async-await
我有一个非常简单的代码片段,用于测试如何在 Main() 中调用 Task<> 方法
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
private static async Task<int> F1(int wait = 1)
{
await Task.Run(() => Thread.Sleep(wait));
Console.WriteLine("finish {0}", wait);
return 1;
}
public static async void Main(string[] args)
{
Console.WriteLine("Hello World!");
var task = F1();
int f1 = await task;
Console.WriteLine(f1);
}
}
Run Code Online (Sandbox Code Playgroud)
它无法编译,因为:
(1) F1 是异步的,所以 Main() 必须是“异步的”。
(2) 编译器说:
error CS5001: Program does not contain a static 'Main' method suitable for an entry point
Run Code Online (Sandbox Code Playgroud)
所以如果我删除 Main 的“async”,编译器会说:
error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
Run Code Online (Sandbox Code Playgroud)
我可以在这里添加或删除“async”关键字。如何使它工作?非常感谢。
Joh*_*lay 10
您的Main方法不符合此处列出的有效签名之一。
你可能想使用这个:
public static async Task Main(string[] args)
Run Code Online (Sandbox Code Playgroud)
Task需要返回A ,以便运行时知道该方法何时完成;这无法通过void.
编译器通过生成合成入口点来实现这一点:
private static void $GeneratedMain(string[] args) =>
Main(args).GetAwaiter().GetResult();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1805 次 |
| 最近记录: |