简体   繁体   中英

SendAsync is blocking UI thread

Trying to convert part of my program into asynchronous http client call. Took out part of code (which is below) to test. Basically an async'ed button with non-blocking (should be to my knowledge) SendAsync(). It should not block UI thread, am I correct? It still blocks it for a reason I cannot currently see.

I've spent last 2 days trying to figure out whats wrong. I implemented non-blocking file write logging and email send features and they work correctly.

Could someone point out what am I doing wrong please?

private async void button2_Click(object sender, EventArgs e)
    {
    NetworkCredential differentCredToPass = new NetworkCredential("user", "*****", "domain");
    WebProxy wcProxy = new WebProxy("1.1.1.1", 8080);
    wcProxy.UseDefaultCredentials = false;
    wcProxy.Credentials = differentCredToPass;
    var httpHandler = new HttpClientHandler();
    httpHandler.UseProxy = true;
    httpHandler.UseDefaultCredentials = false;
    httpHandler.Proxy = wcProxy;
    using(HttpClient httpClient = new HttpClient(httpHandler) )
        {
        try
            {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://cisco.Com");
            HttpResponseMessage response = await httpClient.SendAsync(request);
            textBox1.AppendText(response.StatusCode.ToString() + Environment.NewLine);
            }
        catch (Exception ex)
            {
            textBox1.AppendText(ex.Message.ToString() + Environment.NewLine);
            throw;
            }
        }
    }

non-blocking (should be to my knowledge) SendAsync()

Well, yes and no. Unfortunately, for historical reasons, SendAsync is not purely asynchronous. Specifically, it does DNS lookup and proxy resolution synchronously. So, to make this fully nonblocking, you would need to wrap that call in a Task.Run :

HttpResponseMessage response = await Task.Run(() => httpClient.SendAsync(request));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM