首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >中止WebClient.DownloadFileAsync操作

中止WebClient.DownloadFileAsync操作
EN

Stack Overflow用户
提问于 2012-04-26 11:30:10
回答 1查看 11.7K关注 0票数 4

安全取消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)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-26 11:59:20

我不知道为什么调用CancelAsync会有异常。

我使用WebClient处理当前项目中的paralell下载,在调用CancelAsync时,事件DownloadFileCompleted由WebClient引发,其中属性Cancelled为true。我的事件处理程序如下所示:

代码语言:javascript
复制
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");
}

取消的方法很简单:

代码语言:javascript
复制
/// <summary>
/// If downloading, cancels a download in progress.
/// </summary>
public virtual void Cancel()
{
    if (this.client != null)
    {
        this.client.CancelAsync();
    }
}
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10332506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档