[英]Aborting a WebClient.DownloadFileAsync operation
What is the best way to cancel a DownloadFileAsync operation safely? 安全取消DownloadFileAsync操作的最佳方法是什么?
I have a thread (background worker) that kicks off the download and manages other aspects of it and that I end when I see that the thread has CancellationPending == true.
我有一个线程(后台工作者)启动下载并管理它的其他方面,当我看到线程有
CancellationPending == true.
时我结束CancellationPending == true.
After kicking off the download, the thread will sit and spin until the download has completed, or the thread is cancelled. 开始下载后,线程将一直旋转直到下载完成,或线程被取消。
If the thread is cancelled, I want to cancel the download. 如果线程被取消,我想取消下载。 Is there a standard idiom for doing this?
这样做有标准的习惯用法吗? I've tried
CancelAsync
, but I get a WebException from it (aborted). 我尝试过
CancelAsync
,但是我从中获取了一个WebException(中止)。 I'm not sure this is a clean way of doing the cancel. 我不确定这是一种干净的取消方式。
Thanks. 谢谢。
Edit: the first exception is and object disposed one on the internal stream (call stack): 编辑:第一个异常是和对象在内部流(调用堆栈)上处理一个:
System.dll!System.Net.Sockets.NetworkStream.EndRead(System.IAsyncResult asyncResult) System.dll!System.Net.PooledStream.EndRead(System.IAsyncResult asyncResult)
System.dll!System.Net.Sockets.NetworkStream.EndRead(System.IAsyncResult asyncResult)System.dll!System.Net.PooledStream.EndRead(System.IAsyncResult asyncResult)
I'm not sure why you would get an exception from calling CancelAsync. 我不确定为什么你会因调用CancelAsync而得到异常。
I use WebClient to handle paralell downloads in our current project, and upon calling CancelAsync the event DownloadFileCompleted
is raised by WebClient, where the property Cancelled
is true. 我使用WebClient来处理当前项目中的并行下载,并且在调用CancelAsync时,WebClient会引发事件
DownloadFileCompleted
,其中属性Cancelled
为true。 My event handler looks like this: 我的事件处理程序如下所示:
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");
}
And the cancelling method is simply: 取消方法很简单:
/// <summary>
/// If downloading, cancels a download in progress.
/// </summary>
public virtual void Cancel()
{
if (this.client != null)
{
this.client.CancelAsync();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.