安全取消 DownloadFileAsync 操作的最佳方法是什么?
我有一个线程(后台工作人员),它启动下载并管理它的其他方面,当我看到该线程有时我结束CancellationPending == true.
开始下载后,线程将静止并旋转,直到下载完成或线程被取消。
如果线程被取消,我想取消下载。有这样做的标准习惯用法吗?我试过了CancelAsync
,但我从中得到一个 WebException(已中止)。我不确定这是一种干净的取消方式。
Thanks.
编辑:第一个例外是对象在内部流(调用堆栈)上处置一个:
System.dll!System.Net.Sockets.NetworkStream.EndRead(System.IAsyncResult asyncResult)
System.dll!System.Net.PooledStream.EndRead(System.IAsyncResult asyncResult)
我不确定为什么调用 CancelAsync 会出现异常。
我使用 WebClient 来处理当前项目中的并行下载,并在调用 CancelAsync 事件时DownloadFileCompleted
由 WebClient 引发,其中属性Cancelled
是真的。我的事件处理程序如下所示:
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();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)