This works fine:
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();
}
While this code (notice the async/await pattern)...:
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();
}
... throws the following exception:
System.Net.WebException
The request was aborted: The request was canceled.
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
How can I cancel a task started with await WebClient.DownloadFileTaskAsync() without throwing an exception?
_webClientalmost instantly, which means it's probably disposed by the timeCancelAsync()gets called. I'd guess that CancelAsync is returning an error in a Task which you're ignoring because you're not awaiting it. So it appears to work fine, but the request isn't actually getting canceled.AsyncCompletedEventArgs.Cancelledstatus in theWebClient.DownloadFileCompletedevent handler.usingstatement and neglect to await async tasks you'll get burned for it. But based on this comment and the source code,WebClientbasically ignores getting disposed.