.NET 4.5 中 WPF 中的异步事件处理程序无响应 [英] Unresponsiveness with async event handlers in WPF in .NET 4.5
问题描述
我创建了一个简单的异步操作,当单击按钮时它会被踢出.完整代码如下:
I have created a simple async operation which is being kicked of when the button is clicked. Here is the whole code:
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private async void Button_Click_1(object sender, RoutedEventArgs e) {
var htmlString = await DowloadPage("http://example.com");
txtBlock1.Text = htmlString;
}
public async Task<string> DowloadPage(string uri) {
using (WebClient client = new WebClient()) {
var htmlString = await client.DownloadStringTaskAsync(uri);
return htmlString;
}
}
}
很简单.但是当我单击按钮时,我在 UI 线程上遇到了无响应的情况.当我在下载页面时尝试在窗口中移动时,我无法移动.
Very easy. But when I click the button, I experience unresponsiveness on the UI thread. When I try to move around the window while the page is being downloaded, I am unable to.
知道出了什么问题吗?
我在 .NET 4.5 中尝试了 HttpClient,结果如预期的一样好:
I tried with HttpClient in .NET 4.5 and it worked out pretty great as expected:
public async Task<string> DowloadPage(string uri) {
using (HttpClient client = new HttpClient()) {
var response = await client.GetAsync(uri);
var htmlString = await response.Content.ReadAsStringAsync();
return htmlString;
}
}
推荐答案
WebClient
使用 HttpWebRequest
,不幸的是 不是很异步,即使您使用异步"方法.它至少会进行阻塞式 DNS 查找.它也可能在代理协商和/或初始 HTTP 连接期间阻塞.
WebClient
uses HttpWebRequest
, which unfortunately is not very asynchronous, even if you use the "asynchronous" methods. It does a blocking DNS lookup, at least. It may also block during proxy negotiation and/or the initial HTTP connection.
HttpClient
的旧版本只是使用了 HttpWebRequest
的包装器.我请求了一个真正异步的HttpClient
,但从未听到响应.上次我检查HttpClient
,它仍然是MVC的一部分;那时 ASP.NET Web API 还没有出现,所以他们可能从那时起修复了 HttpClient
.或者WebClient
和 HttpClient
在你的机器上的行为差异可能只是与 DNS 缓存或类似的东西有关.
An older release of HttpClient
was just using a wrapper around HttpWebRequest
. I requested a truly-asynchronous HttpClient
, but never heard a response. The last time I checked HttpClient
, it was still part of MVC; ASP.NET Web API wasn't around at that time, so they may have fixed HttpClient
since then. Or the difference in behavior between WebClient
and HttpClient
on your machine may just have to do with DNS caches or some such.
这篇关于.NET 4.5 中 WPF 中的异步事件处理程序无响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!