【问题标题】:C#: call async method inside Main of console application leads to compilation failure [closed]C#:在控制台应用程序的 Main 中调用异步方法导致编译失败 [关闭]
【发布时间】: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”关键字。如何让它发挥作用?非常感谢。

【问题讨论】:

标签: c# asynchronous async-await task main


【解决方案1】:

您的Main 方法不符合here 列出的有效签名之一。

你可能想用这个:

public static async Task Main(string[] args)

需要返回一个Task,以便运行时知道方法何时完成;这无法通过void 确定。

编译器通过生成合成入口点来实现这一点:

private static void $GeneratedMain(string[] args) => 
    Main(args).GetAwaiter().GetResult();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多