这很好用:
private WebClient _webClient;
private void ButtonStart_Click(object sender, RoutedEventArgs e) {
using (_webClient = new WebClient()) {
_webClient.DownloadFileTaskAsync("https://speed.hetzner.de/100MB.bin", @"D:\100MB.bin");
}
}
private void ButtonStop_Click(object sender, RoutedEventArgs e) {
_webClient.CancelAsync();
}
虽然此代码(注意异步/等待模式)...:
private WebClient _webClient;
private async void ButtonStart_Click(object sender, RoutedEventArgs e) {
using (_webClient = new WebClient()) {
await _webClient.DownloadFileTaskAsync("https://speed.hetzner.de/100MB.bin", @"D:\100MB.bin");
}
}
private void ButtonStop_Click(object sender, RoutedEventArgs e) {
_webClient.CancelAsync();
}
...抛出以下异常:
系统.Net.WebException
请求被中止:请求被取消。
at System.Net.ConnectStream.EndRead(IAsyncResult asyncResult)
at System.Net.WebClient.DownloadBitsReadCallbackState(DownloadBitsState state, IAsyncResult result)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at WpfApp1.MainWindow.<ButtonStart_Click>d__2.MoveNext() in WpfApp1\MainWindow.xaml.cs:line 19
如何在await WebClient.DownloadFileTaskAsync()不引发异常的情况下取消开始的任务?
紫衣仙女
撒科打诨
相关分类