在“等待DownloadTaskAsync”上调用WebClient.CancelAsync时出现WebException

Oti*_*iel 1 c# webclient async-await

这很好用:

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();
}
Run Code Online (Sandbox Code Playgroud)

虽然这段代码(注意异步/等待模式)...:

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();
}
Run Code Online (Sandbox Code Playgroud)

...引发以下异常:

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
Run Code Online (Sandbox Code Playgroud)

如何取消开始的任务而await WebClient.DownloadFileTaskAsync()不会引发异常?

Ste*_*ary 7

唯一的例外是它应该如何工作。

如果您不希望该异常传播到事件处理程序之外,请捕获该异常。