Why doesn't the async method return immediately?

I thought this is a sane pattern that can be used to call WebClient DownloadData asynchronously in an event handler:

private async void button1_Click(object sender, EventArgs e)
{
    WebClient wc = new WebClient();
    //wc.Proxy = null;
    byte[] bytes = await wc.DownloadDataTaskAsync("http://www.google.com");
    label1.Text = Encoding.ASCII.GetString(bytes);
}

      

But I can find DownloadDataTaskAsync blocks for about 5 seconds before returning (unless the expression wc.Proxy = null is met). What's the point of the expected method if it can, on a whim, do non-trivial work before even returning the task?

Presumably this means I have to be safe. I should never call the xAsync methods like above, but instead should always complete them in Task.Run () to be sure. Or not?

+3


source to share


2 answers


This is a known issue with WebClient

/ HttpWebRequest

: proxies and DNS queries are always done synchronously. This is a bug, but Microsoft has chosen not to fix it for backward compatibility reasons.



First of all, I recommend using HttpClient

. If that doesn't work and you want async, you can end the call in Task.Run

.

+6


source


It turns out WebClient.DownloadDataTaskAsync is calling HttpWebRequest.BeginGetResponse

MSDN points out:

The BeginGetResponse method requires some synchronous configuration tasks to complete (DNS resolution, proxy discovery, and TCP socket connections, for example) before this method becomes asynchronous. As a result, this method should never be called on the user interface (UI) thread because it can take a significant amount of time (up to several minutes depending on network settings) to complete the initial synchronous configuration task before an error exception is thrown or the method succeeds.

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse(v=vs.110).aspx



Unfortunately, the MSDN documentation for WebClient.DownloadDataTaskAsync says:

This operation will not be blocked.

which doesn't seem to be strict.

0


source







All Articles