我不确定为什么调用 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();
}
}