Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How expensive is c# Async and await

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?

like image 839
Parv Sharma Avatar asked Apr 13 '13 10:04

Parv Sharma


2 Answers

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.

like image 121
Hans Passant Avatar answered Nov 16 '22 20:11

Hans Passant


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.
like image 33
Branko Dimitrijevic Avatar answered Nov 16 '22 21:11

Branko Dimitrijevic