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/..., , , .