I write a simple async-await code following. As far as I know, when await
in FetchAndShowHeaders
method is hit, the method's continuation is the rest of the method that is Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(response.Headers.ToString()));
.
The point I don't understand that while await
is not yet hit in top-level main
method, how is the method completed?
I expect typically that all dots are written, and the method prints the result. But in the middle of writing dots, in which case main()
runs, the method completes. How come?
Console.WriteLine("soner1");
Task q = FetchAndShowHeaders("http://www.fultonbank.com");
Console.WriteLine("soner2");
for (int i = 0; i < 500_000_0; i++)
{
for (int ii = 0; ii < 500; ii++)
{
if (i % 500_000 == 0)
Console.Write(".");
}
}
Console.WriteLine("\nsoner3");
await q;
Console.WriteLine("soner4");
return;
async Task FetchAndShowHeaders(string url)
{
using var w = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Head, url);
var response = await w.SendAsync(req, HttpCompletionOption.ResponseHeadersRead);
Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(
response.Headers.ToString()));
}
Output: (think about the output word wrap is enabled)
/Users/soner/RiderProjects/yea/yea/bin/Debug/net6.0/yea
soner1
soner2
......................................................................................................
...........................................................................
.........................................................................................................
.................................................."Date:
Mon, 28 Aug 2023 12:24:07 GMT\nConnection: keep-alive\nSet-Cookie: AWSB9/69VjCnga384ol7q; Expires=Mon,
04 Sep 2023 12:24:06 GMT; Path=/; SameSite=None; Secure, ASP.NET_SessionId=i2hpoollqqqqud1a
pz2gqac; path=/; HttpOnly; SameSite=Lax, ASP.NET_SessionId=i2hqqqd1apz2gqac;
path=/; HttpOnly; SameSite=Lax, Fulton.Foundation.ContactIdent
ification.Cookies.ContactIdentificationCookieManagerblablalblalbla"
............................
..........................
.........................................................................................................................
..........................
..........................
.........................................................................
.................................................................
soner3
soner4
Process finished with exit code 0.