我有一个非常简单的代码片段,用于测试如何在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);
}
}
它不能编译,原因如下:
(1) F1 是异步的,因此 Main() 必须是 "async"。
(2) 编译器报错:
error CS5001: Program does not contain a static 'Main' method suitable for an entry point
所以如果我移除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'.
我可以在这里添加或移除 "async" 关键字。该如何使其正常工作?非常感谢。
public static async Task Main()
。 - Pavel AnikhouskiMain
withasync
should be returningTask
notvoid
- Ehsan Sajjad