安全取消DownloadFileAsync操作的最佳方法是什么?
我有一个线程(后台工作人员),它启动下载并管理它的其他方面,当我看到该线程在开始下载后具有CancellationPending == true.时,线程将一直处于旋转状态,直到下载完成,或者线程被取消。
如果线程被取消,我想取消下载。这样做有标准的成语吗?我尝试过CancelAsync,但是我从它得到了一个WebException (中止)。我不确定这是不是取消的一个干净的方式。
谢谢。
编辑:第一个异常是在内部流(调用堆栈)上释放了一个和对象:
世界银行( System.dll!System.Net.Sockets.NetworkStream.EndRead(System.IAsyncResult System.dll!System.Net.PooledStream.EndRead(System.IAsyncResult asyncResult) (System.dll!System.Net.PooledStream.EndRead(System.IAsyncResult asyncResult)
发布于 2012-04-26 11:59:20
我不知道为什么调用CancelAsync会有异常。
我使用WebClient处理当前项目中的paralell下载,在调用CancelAsync时,事件DownloadFileCompleted由WebClient引发,其中属性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();
}
}https://stackoverflow.com/questions/10332506
复制相似问题