【发布时间】:2020-06-14 15:11:41
【问题描述】:
我有一个非常简单的代码 sn-p,用来测试如何在 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() 必须是“异步”的。
(2) 编译器说:
error CS5001: Program does not contain a static 'Main' method suitable for an entry point
所以如果我删除 Main 的“异步”,编译器会说:
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”关键字。如何让它发挥作用?非常感谢。
【问题讨论】:
-
考虑用'async'修饰符标记这个方法并将其返回类型更改为'Task'编译器已经告诉你一切,尝试使用
public static async Task Main() -
Main和async应该返回Task而不是void
标签: c# asynchronous async-await task main