2

试图将我的程序的一部分转换为异步 http 客户端调用。取出部分代码(如下)进行测试。基本上是一个非阻塞的异步按钮(据我所知)SendAsync()。它不应该阻塞 UI 线程,对吗?由于我目前看不到的原因,它仍然会阻止它。

我花了两天时间试图找出问题所在。我实现了非阻塞文件写入日志和电子邮件发送功能,它们工作正常。

有人可以指出我做错了什么吗?

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;
            }
        }
    }
4

1 回答 1

4

非阻塞(据我所知)SendAsync()

嗯,是的,也不是。不幸的是,由于历史原因,SendAsync并不是纯粹的异步。具体来说,它同步进行 DNS 查找和代理解析。因此,要使其完全无阻塞,您需要将该调用包装在 a 中Task.Run

HttpResponseMessage response = await Task.Run(() => httpClient.SendAsync(request));
于 2019-05-07T21:01:56.127 回答