SendAsync正在阻止UI线程 [英] SendAsync is blocking UI thread

查看:108
本文介绍了SendAsync正在阻止UI线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试将我的程序的一部分转换为异步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;
            }
        }
    }

推荐答案

非阻塞(据我所知)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));

这篇关于SendAsync正在阻止UI线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆