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));
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcgcbje
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20