安全取消 DownloadFileAsync 操作的最佳方法是什么?
我有一个线程(后台 worker )开始下载并管理它的其他方面,当我看到线程有 CancellationPending == true 时我结束。
开始下载后, 线程将坐下并旋转直到下载完成,或者线程被取消。
如果线程被取消,我想取消下载。这样做有标准的成语吗?我试过 CancelAsync
,但我从中得到了一个 WebException(已中止)。我不确定这是执行取消的简洁方法。
谢谢。
编辑:第一个异常是对象在内部流(调用堆栈)上处理:
System.dll!System.Net.Sockets.NetworkStream.EndRead(System.IAsyncResult asyncResult) System.dll!System.Net.PooledStream.EndRead(System.IAsyncResult asyncResult)
最佳答案
我不确定为什么调用 CancelAsync 会出现异常。
我在当前项目中使用 WebClient 处理并行下载,在调用 CancelAsync 时,WebClient 引发事件 DownloadFileCompleted
,其中属性 Cancelled
为 true。我的事件处理程序如下所示:
private void OnDownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled)
{
this.CleanUp(); // Method that disposes the client and unhooks events
return;
}
if (e.Error != null) // We have an error! Retry a few times, then abort.
{
if (this.retryCount < RetryMaxCount)
{
this.retryCount++;
this.CleanUp();
this.Start();
}
// The re-tries have failed, abort download.
this.CleanUp();
this.errorMessage = "Downloading " + this.fileName + " failed.";
this.RaisePropertyChanged("ErrorMessage");
return;
}
this.message = "Downloading " + this.fileName + " complete!";
this.RaisePropertyChanged("Message");
this.progress = 0;
this.CleanUp();
this.RaisePropertyChanged("DownloadCompleted");
}
取消方法很简单:
/// <summary>
/// If downloading, cancels a download in progress.
/// </summary>
public virtual void Cancel()
{
if (this.client != null)
{
this.client.CancelAsync();
}
}
关于c# - 中止 WebClient.DownloadFileAsync 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10332506/