问题描述
您好,
我有一个非常基本的WPF程序,它尝试使用WebClient DownloadFileTaskAsync下载文件。该文件已下载,但在下载过程中,WPF窗口冻结。我在这里缺少什么?
I have a very basic WPF program which tries to download a file using WebClient DownloadFileTaskAsync. The file is downloaded, but during the download the WPF window is freezes. What am I missing here?
我的代码:
公共部分类MainWindow:窗口
; {
private string url =" http://www.mywebsite.com" ;;
private string localFile =" d:\test.txt";
$
public MainWindow()
{
InitializeComponent();
}
private async void startButton_Click(object sender,RoutedEventArgs e)
{
await DownloadFileAsync();
}
private async Task DownloadFileAsync()
{
使用(WebClient webClient = new WebClient())
{
等待webClient.DownloadFileTaskAsync(url,localFile);
}
}
}
public partial class MainWindow : Window
{
private string url = "http://www.mywebsite.com";
private string localFile = "d:\test.txt";
public MainWindow()
{
InitializeComponent();
}
private async void startButton_Click(object sender, RoutedEventArgs e)
{
await DownloadFileAsync();
}
private async Task DownloadFileAsync()
{
using (WebClient webClient = new WebClient())
{
await webClient.DownloadFileTaskAsync(url, localFile);
}
}
}
推荐答案
如果你不这样做,那么它可能会显得冻结。您可以添加另一个按钮并尝试在下载过程中单击此按钮,它会起作用。
If you dont, then it might appear frozen. You can add another button and try clicking this while the download is happening, it would work.
这篇关于async / await冻结WPF窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!