• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

SendAsync正在阻止UI线程

用户头像
it1352
帮助1

问题说明

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

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

正确答案

#1

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

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

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

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));

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcgcbje
系列文章
更多 icon
同类精品
更多 icon
继续加载