尝试将程序的一部分转换为异步http客户端调用。
取出部分代码(如下)进行测试。
基本上是一个非阻塞的异步按钮(据我所知)sendaync()。它不应该阻塞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;
            }
        }
    }

最佳答案

非阻塞(据我所知)sendaync()
好吧,是和否。不幸的是,由于历史原因,SendAsync不是完全异步的。具体来说,它同时进行dns查找和代理解析。因此,要使此完全非阻塞,您需要将该调用包装为一个Task.Run

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

10-07 14:53