I have found the following example in Jon Skeet's "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 expected that this code would deadlock, but it does not.
As I see it, it works this way:
Mainmethod callsGetPageLengthAsyncsynchronously within the main thread.GetPageLengthAsyncmakes an asynchronous request and immediately returnsTask<int>toMainsaying "wait for a while, I will return you an int in a second".Maincontinues execution and stumbles uponlengthTask.Resultwhich causes the main thread to block and wait forlengthTaskto finish its work.GetStringAsynccompletes and waits for main thread to become available to executeLengthand start continuation.
But it seems like I misunderstand something. Why doesn't this code deadlock?
The code in this StackOverflow question about await/async deadlock seems to do the same, but deadlocks.