如何在Main中使用await

时间:2014-07-22 18:15:17

标签: c# task

我编写了一个测试应用程序来帮助我理解await / async。我有一个方法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";
        }
    }

1 个答案:

答案 0 :(得分:0)

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