recently was experimenting with async and await using c#. This is my code
private async void button1_Click( object sender, EventArgs e )
{
textBox1.Text = string.Empty;
var client = new WebClient();
var sw = Stopwatch.StartNew();
var downloadStringTask = client.DownloadStringTaskAsync("http://www.google.com");
textBox1.Text += "Downloading string async "+sw.ElapsedMilliseconds;
sw.Restart();
await downloadStringTask;
textBox1.Text += Environment.NewLine + "Downloaded "+sw.ElapsedMilliseconds;
sw.Stop();
}
and this the output im getting in textbox1.text
Downloading string async 5698
Downloaded 666
this means only calling the DownloadStringTaskAsync()
is taking around 5.6 Seconds
to execute where as actual downloading is taking <1 second
. When the reason this method is to be used is to save Thread Resources.
If this is true is there any actual case where this method of WebClient class should be used?? Or im just thinking in totally incorrect terms?
I'm getting about 300 msec the first time, 0 msec every time after that. About what I'd expect. There is always a chunk of overhead when you first use code. At a minimum you are measuring the cost of getting the System.Net code getting loaded into your program and initialized. WebClient appears to have some overhead as well, I'm for example seeing an exception getting caught and handled when it looks through the registry for a web proxy. Basic stuff that needs to be done before something can be done asynchronously.
Still, 5.7 seconds is a very long time. You ought to be looking at environmental stuff, other parts of your machine that want to get involved whenever you are doing something internetty. Like that web proxy, it might be set to auto-configure and that takes time. Or like your anti-malware software or firewall getting excited about you starting to use an outbound IP address. Etcetera, lots of moving parts involved with networking and it is never the same.
You are measuring the setup time. On my machine (and Internet connection), the first call produces:
Downloading string async 2636 // Varies wildly, can be up to 15s on some runs.
Downloaded 385
While the subsequent calls consistently produce:
Downloading string async 0
Downloaded 289 // With small variations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With