中止WebClient.DownloadFileAsync操作

Rob*_*son 3 c#

安全取消DownloadFileAsync操作的最佳方法是什么?

我有一个线程(后台工作者)启动下载并管理它的其他方面,当我看到线程已经CancellationPending == true. 开始下载后,线程将停止并旋转,直到下载完成,或者线程被取消.

如果线程被取消,我想取消下载.这样做有标准的习惯用法吗?我试过了CancelAsync,但是我从中获取了一个WebException(中止).我不确定这是一种干净的取消方式.

谢谢.

编辑:第一个异常是和对象在内部流(调用堆栈)上处理一个:

System.dll!System.Net.Sockets.NetworkStream.EndRead(System.IAsyncResult asyncResult)System.dll!System.Net.PooledStream.EndRead(System.IAsyncResult asyncResult)

Ama*_*ein 7

我不确定为什么你会因调用CancelAsync而得到异常.

我使用WebClient来处理当前项目中的并行下载,并且在调用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");
}
Run Code Online (Sandbox Code Playgroud)

取消方法很简单:

/// <summary>
/// If downloading, cancels a download in progress.
/// </summary>
public virtual void Cancel()
{
    if (this.client != null)
    {
        this.client.CancelAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)