4

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

我有一个线程(后台工作人员),它启动下载并管理它的其他方面,当我看到线程有时我结束在CancellationPending == true. 开始下载后,线程将坐下来旋转直到下载完成,或者线程被取消。

如果线程被取消,我想取消下载。这样做有标准的成语吗?我试过CancelAsync了,但我得到了一个 WebException (中止)。我不确定这是一种干净的取消方式。

谢谢。

编辑:第一个例外是对象在内部流(调用堆栈)上放置一个:

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

4

1 回答 1

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");
}

取消方法很简单:

/// <summary>
/// If downloading, cancels a download in progress.
/// </summary>
public virtual void Cancel()
{
    if (this.client != null)
    {
        this.client.CancelAsync();
    }
}
于 2012-04-26T11:59:20.287 回答