我创建了一个简单的异步操作,当单击按钮时它会被踢掉。这是整个代码:
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 线程上遇到无响应的情况。当我在下载页面时尝试在窗口中移动时,我无法做到。
知道出了什么问题吗?
编辑:
我在 .NET 4.5 中使用 HttpClient 进行了尝试,结果与预期的一样好:
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;
}
}