这工作正常:
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();
}
...引发以下异常:
System.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()
开头的任务而不会引发异常? 最佳答案
唯一的例外是它应该如何工作。
如果您不希望该异常传播到事件处理程序之外,请捕获该异常。
关于c# - 在“await DownloadTaskAsync”上调用WebClient.CancelAsync时出现WebException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55870469/