As reading C# in Depth of Jon Skeet, I have come across the following expression.
You’re setting
label.Text
at the start and end of the method, so it’s reasonable to assume that both of those statements are executed on the UI thread, and yet you’re clearly not blocking the UI thread while you wait for the web page to download. The trick is that the method returns as soon as it hits the await expression.
When I click the button, I expect that Debug.WriteLine("end method " + DateTime.Now.ToString("ss.fffff"));
runs and prints out without waiting for the website's response. However, it prints out after the response is received. Doesn't it conflict with the bold text part in the quotation? I have tested it by slowing down Visual Studio's connection speed by NetBalancer. The Debug.Writeline(..)
part doesn't print out immediately after hitting await as opposed to the saying. Both the UI's output and that of debug yield same nanosecs. Where do I do mistake? I must be wrong since he cannot be mistaken (:
public class AsyncIntro : Form
{
private static readonly HttpClient Client = new HttpClient();
private readonly Label _label;
private readonly Button _button;
public AsyncIntro()
{
_label = new Label
{
Location = new Point(10, 30),
Text = "Length"
};
_button = new Button
{
Location = new Point(10, 60),
Text = "Click"
};
_button.Click += DisplayWebSiteLength;
AutoSize = true;
Controls.Add(_label);
Controls.Add(_button);
}
public sealed override bool AutoSize { get; set; }
private async void DisplayWebSiteLength(object sender, EventArgs e)
{
_label.Text = "Fetching...";
var text = await Client.GetStringAsync("http://csharpindepth.com");
_label.Text = text.Length.ToString() + " " + DateTime.Now.ToString("ss.fffff");
Debug.WriteLine("end method " + DateTime.Now.ToString("ss.fffff"));
}
private static void Main()
{
Application.Run(new AsyncIntro());
}
}