c# - 中止 WebClient.DownloadFileAsync 操作

标签 c#

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

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

如果线程被取消,我想取消下载。这样做有标准的成语吗?我试过 CancelAsync,但我从中得到了一个 WebException(已中止)。我不确定这是执行取消的简洁方法。

谢谢。

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

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

最佳答案

我不确定为什么调用 CancelAsync 会出现异常。

我在当前项目中使用 WebClient 处理并行下载,在调用 CancelAsync 时,WebClient 引发事件 DownloadFileCompleted,其中属性 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();
    }
}

关于c# - 中止 WebClient.DownloadFileAsync 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10332506/

相关文章:

c# - BrowseForFolder 对话框 : center and make TopMost

c# - 单击按钮后 Rowcommand 不触发

c# - 当 TextBox 插入符号更改时,是否有机会引发事件?

c# - 对于内存中添加的新实体,为什么 EF 不会将 EntityState 显示为“已添加”?

c# - 更新命令在传递 DataRow 时需要有效的 insertCommand

c# - 如何安全有效地缓存ADO.NET命令?

c# - 如何验证一个类型是否重载/支持某个运算符?

c# - 尝试在 WPF 中构建查询生成器控件

c# - Windows Phone 8.1 位置跟踪

c# - 修剪 DataGridView 单元格中的空白区域