3

I have written a test app to help me understand await/async. I have a method MethodAsync1() which works fine. However when I call it from Main(), I cant figure out how to await for the MethodAsync1() to complete. See code below.

   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";
        }
    }
spiderplant0
  • 3,710
  • 11
  • 48
  • 86

1 Answers1

0

I don't think this is possible with the main method. Besides that it will be just a signature. In this specific case I will use the Result property of the Task in order to block until a result is given.

LazyOfT
  • 1,428
  • 7
  • 19