代码之家  ›  专栏  ›  技术社区  ›  Troskyvs

C#:在控制台应用程序的Main中调用异步方法会导致编译失败[closed]

  •  0
  • Troskyvs  · 技术社区  · 6 年前

    我有一个非常简单的代码片段,用来测试如何调用Task<&燃气轮机;Main()中的方法

    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);
        }
    }
    

    它无法编译,因为:

    (2) 编译器说:

    error CS5001: Program does not contain a static 'Main' method suitable for an entry point
    

    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”关键字。如何让它工作?谢谢。

    1 回复  |  直到 6 年前
        1
  •  11
  •   Johnathan Barclay    6 年前

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

    public static async Task Main(string[] args)
    

    A. Task 需要返回,以便运行时知道方法何时完成;这一点无法用计算机来确定 void

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

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