简体   繁体   English

SendAsync正在阻止UI线程

[英]SendAsync is blocking UI thread

Trying to convert part of my program into asynchronous http client call. 尝试将我的程序的一部分转换为异步http客户端调用。 Took out part of code (which is below) to test. 拿出部分代码(在下面)进行测试。 Basically an async'ed button with non-blocking (should be to my knowledge) SendAsync(). 基本上是一个具有非阻塞的异步按钮(据我所知)SendAsync()。 It should not block UI thread, am I correct? 它不应该阻止UI线程,对吗? 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() 非阻塞(据我所知)SendAsync()

Well, yes and no. 好,是的,不是。 Unfortunately, for historical reasons, SendAsync is not purely asynchronous. 不幸的是,由于历史原因, SendAsync并非纯粹是异步的。 Specifically, it does DNS lookup and proxy resolution synchronously. 具体来说,它同步进行DNS查找和代理解析。 So, to make this fully nonblocking, you would need to wrap that call in a Task.Run : 因此,要使其完全无阻塞,您需要将该调用包装在Task.Run

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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