Why is this async / await code NOT deadlocking?

I found the following example in Jon Skeet "C # in depth. 3rd edition":

static async Task<int> GetPageLengthAsync(string url)
{
    using (HttpClient client = new HttpClient())
    {
        Task<string> fetchTextTask = client.GetStringAsync(url);
        int length = (await fetchTextTask).Length;
        return length;
    }
}

public static void Main()
{
    Task<int> lengthTask = GetPageLengthAsync("http://csharpindepth.com");
    Console.WriteLine(lengthTask.Result);
}

I would expect this code to come to a standstill, but it is not.

As I see it, it works as follows:

  • MainThe method calls GetPageLengthAsyncsynchronously in the main thread.
  • GetPageLengthAsyncmakes an asynchronous request and immediately returns Task<int>to Main, saying "wait a while, I will return you int in a second."
  • Maincontinues execution and stumbles upon lengthTask.Result, which causes the main thread to block and wait for completion lengthTask.
  • GetStringAsyncshuts down and waits until the main thread becomes available for execution Lengthand continues to continue.

, , - .
? qaru.site/questions/41190/..., , , .

+4
1

await , ( ) ASP.NET( ).

GUI , .Result. await .

​​ASP.NET , .Result .

PS VS 15.3:

Visual Studio 2017 15.3 Preview 2 (gasp) . :

public static Task Main()
{
    var length = await GetPageLengthAsync("http://csharpindepth.com");
    Console.WriteLine(length);
}
+8

Source: https://habr.com/ru/post/1679253/


All Articles