【问题标题】:How to use await within Main [duplicate]如何在 Main [重复] 中使用 await
【发布时间】:2014-07-22 18:15:16
【问题描述】:

我编写了一个测试应用程序来帮助我理解等待/异步。我有一个方法MethodAsync1() 可以正常工作。但是,当我从 Main() 调用它时,我无法弄清楚如何等待 MethodAsync1() 完成。请参阅下面的代码。

   class Program
    {
        static void Main(string[] args)
        {
            Debug.WriteLine(DateTime.Now + " Main()1");
            Task<String> v1 = MethodAsync1();
            Debug.WriteLine(DateTime.Now + " Main()2 - prints out before Method1 finishes");

            // I now want to wait for MethosAsync1() to complete before I go further.
            // This line has error:
            // Error    1   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'.  
            String v2 = await v1;

            Debug.WriteLine(DateTime.Now + " Main()3 - Method1() now finished");
        }



        static async Task<String> MethodAsync1()
        {
            Debug.WriteLine(DateTime.Now + " Method1()1 ");

            HttpClient client = new HttpClient();
            Task<HttpResponseMessage> responseTask = client.GetAsync("http://bbc.co.uk");

            // Do other stuff
            Debug.WriteLine(DateTime.Now + " Method1()2 ");

            // Wait for it to finish - yield thread back to Main()
            var response= await responseTask;

            // responseTask has completed - so thread goes back here and method returns fully
            Debug.WriteLine(DateTime.Now + " Method1()3 ");

            return "finished";
        }
    }

【问题讨论】:

  • 你能让main也成为async方法吗?
  • 不,它不会让我说:'await1.Program.Main(string[])': an entry point cannot be marked with the 'async' modifier
  • 为什么main 应该是异步的?这是没有意义的。阻塞它的线程直到你得到结果。
  • @spiderplant0 你不能在 main 中等待。使用v1.Result
  • 找到了我自己的问题的答案:stackoverflow.com/a/17579418/120955

标签: c# task


【解决方案1】:

我认为使用 main 方法是不可能的。除此之外,它只是一个签名。在这种特定情况下,我将使用 Task 的 Result 属性来阻止,直到给出结果。

【讨论】:

  • 谢谢你,我会在Result阅读
猜你喜欢
  • 2019-05-24
  • 1970-01-01
  • 2013-12-30
  • 2016-12-16
  • 2018-01-12
  • 1970-01-01
  • 2021-09-26
  • 2015-03-15
  • 2019-12-21
相关资源
最近更新 更多