【发布时间】:2019-09-16 03:16:40
【问题描述】:
这很好用:
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();
}
虽然这段代码(注意 async/await 模式)...:
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() 开始的任务而不引发异常?
【问题讨论】:
-
你怎么知道下载被中止了?
-
我怀疑第一个代码块是否真的可以正常工作:您将几乎立即处理
_webClient,这意味着它可能在CancelAsync()被调用时被处理。我猜 CancelAsync 在您忽略的任务中返回一个错误,因为您没有等待它。所以它看起来工作正常,但请求实际上并没有被取消。 -
@PauloMorgado 通过在
WebClient.DownloadFileCompleted事件处理程序中检查AsyncCompletedEventArgs.Cancelled状态。 -
@StriplingWarrior 好吧,下载停止了,那肯定意味着请求被取消了,不是吗?
-
@Otiel:Touché。我只是想当请求没有取消时你的下载不应该完成。通常,如果你有一个
using语句并且忽略等待异步任务,你会为此而烦恼。但基于this comment 和the source code,WebClient基本上忽略了被处置。
标签: c# async-await webclient