C# 为什么当我点击按钮取消web客户端下载进度时会出现异常?

C# 为什么当我点击按钮取消web客户端下载进度时会出现异常?,c#,.net,winforms,C#,.net,Winforms,在已完成的事件中,我只有一份回报;在“取消”对话框中: private void btnStop_Click(object sender, EventArgs e) { if (this.client != null) this.client.CancelAsync(); } 例外情况: HResult=-2146233079 Message=请求已中止:请求已终止 取消了。Source=下载多文件Stac

在已完成的事件中,我只有一份回报;在“取消”对话框中:

private void btnStop_Click(object sender, EventArgs e)
        {
            if (this.client != null)
                this.client.CancelAsync();
        }
例外情况:

HResult=-2146233079 Message=请求已中止:请求已终止 取消了。Source=下载多文件StackTrace: 在DownloadMultipleFiles.Form1.client\u DownloadFileCompletedObject 发送方,Form1.cs中的AsyncCompletedEventArgs e:第193行 在System.Net.WebClient.OnDownloadFileCompletedAsyncCompletedEventArgs E 在System.Net.WebClient.DownloadFileOperationCompletedObject arg InnerException中:

第193行是:

private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                // handle error scenario
                throw e.Error;
            }
            if (e.Cancelled)
            {
                //client.Dispose(); // Method that disposes the client and unhooks events
                return;
                // handle cancelled scenario
            }

            if (url.Contains("animated") && url.Contains("infra"))
            {
                Image img = new Bitmap(lastDownloadedFile);
                Image[] frames = GetFramesFromAnimatedGIF(img);
                foreach (Image image in frames)
                {
                    countFrames++;
                    image.Save(downloadDirectory + "\\" + fname + ".gif");
                }
            }

            label2.Text = "Download Complete";

            string lastUrl = (string)e.UserState;

            listView1.BeginUpdate();
            foreach (ListViewItem li in listView1.Items)
            {
                if (li.SubItems[2].Text == lastUrl)
                {
                    li.SubItems[0].Text = "Downloaded";
                    li.SubItems.Add("Color");
                    li.SubItems[0].ForeColor = Color.Green;
                    li.UseItemStyleForSubItems = false;
                }
            }
            listView1.EndUpdate();

            tracker.NewFile();
            DownloadFile();
        }
在已完成事件的内部

e、 错误={请求已中止:请求已取消。}

我应该在取消部分的已完成事件中做些什么吗?所有其他id均为返回

出现this.client.CancelAsync;内部不仅会引发取消标志,还会将错误设置为您看到的异常。因此,修复代码的明显方法是交换两个检查

私有无效客户端\u下载FileCompletedObject发送方,AsyncCompletedEventArgs e { //首先检查是否已取消,然后检查是否存在其他异常 如果e.取消 { //client.Dispose;//处理客户端并取消挂起事件的方法 回来 //处理取消的场景 } 如果e.错误!=null { //处理错误场景 抛出e.错误; } ...
throw e.Error;