为什么当我点击按钮取消Web客户端下载进度时我会遇到异常?

时间:2017-03-15 23:02:47

标签: c# .net winforms

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

在完成的活动中,我只有一个回报;在取消中:

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

例外:

  

HResult = -2146233079 Message =请求已中止:请求   取消了。 Source = DownloadMultipleFiles StackTrace:           在DownloadMultipleFiles.Form1.client_DownloadFileCompleted(Object   在Form1.cs中的sender,AsyncCompletedEventArgs e):第193行           在System.Net.WebClient.OnDownloadFileCompleted(AsyncCompletedEventArgs   E)           在System.Net.WebClient.DownloadFileOperationCompleted(Object arg)InnerException:

第193行是:

throw e.Error;

在已完成的活动中。

e.Error = {"请求已中止:请求已取消。"}

我应该在取消部分的已完成事件中做些什么吗?所有id都是回归。

1 个答案:

答案 0 :(得分:1)

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

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

    ...