想要“取消”按钮停止在c#中下载图像

时间:2014-03-25 12:32:50

标签: c# button

使用以下代码我通过HTTPWebRequest从数据库下载图像。

 BackgroundWorker bgWorker = (BackgroundWorker)sender;

 string baseUrl = "http://some path";
 int numIterations = 10;
 for (int i = 0; i < numIterations; i++)
        {
         if (bw.CancellationPending == true)
           {
                e.Cancel = true;
                break;
           }

         else
            {
             HttpWebRequest request = null;
             foreach (var fileName in fileNames)
                   {
                      string url = string.Format(baseUrl, fileName);
                      request = (HttpWebRequest)WebRequest.Create(url);
                      request.Method = "GET";
                      request.ContentType = "application/x-www-form-urlencoded";
                      request.CookieContainer = container;

                      response = (HttpWebResponse)request.GetResponse();
                      Stream stream = response.GetResponseStream();
                      Image img = Image.FromStream(stream);

                      img.Save("some path" + fileName);

                      ZoomThumbnail = img;
                      ZoomSmall = img;
                      ZoomLarge = img;

                      ZoomThumbnail = GenerateThumbnail(ZoomThumbnail, 86, false);

                      ZoomSmall  = GenerateThumbnail(ZoomSmall, 400, false);

                      ZoomLarge = GenerateThumbnail(ZoomLarge, 1200, false);

                      if (img != null)
                      ZoomThumbnail.Save("some path" + fileName + "_Thumb.jpg");
                      ZoomSmall.Save("some path" + fileName + "_ZoomSmall.jpg");
                      ZoomLarge.Save("some path" + fileName + "_ZoomLarge.jpg");
                      System.Threading.Thread.Sleep(200);
                    }
                }

此代码位于ButtonProcess_click下,工作正常。还有一个按钮“取消”。每当用户点击“取消”时,我都希望下载和保存图像的过程停止。有人可以帮忙吗?这是取消按钮的代码,只能禁用“处理”按钮。

ButtonProcess.Enabled = false;
Button btnSender = sender as Button;
btnSender.Enabled = false;
bw.CancelAsync();

1 个答案:

答案 0 :(得分:3)

bw.CancelAsync()行我想使用BackgroundWorker。我还猜测上面的代码是由后台工作者执行的。

但是,在该代码中没有任何地方,我可以看到您实际上正在检查是否应该取消该过程。此外,您将在此行中一次性下载图像:

Image img = Image.FromStream(stream);

这不支持取消。所以问题是:

  1. 你不能取消所有文件的循环,因为你没有检查是否应该取消后台工作者
  2. 您无法取消单个图片下载,因为您一次性下载
  3. 解决方案:

    1. 在循环中,添加条件,如果后台工作程序被取消,则退出循环
    2. 更改图像下载,以便获得大块字节,在循环中调用它并检查取消。
    3. 第一个可能的解决方案:

      if (bw.CancellationPending)
      {
          return;
      }
      

      第二种可能的解决方案:

      Stream stream = response.GetResponseStream();
      byte[] buffer = new byte[512];
      int bytesRead = 0;
      do
      {
          bytesRead = stream.Read(buffer, 0, buffer.Length);
          if (bytesRead > 0)
          {
              // Save the bytes to a memory stream
          }
      }
      while (bytesRead > 0 && !bw.CancellationPending)
      
      if (!bw.CancellationPending)
          img = Image.FromStream(<yourMemoryStream>);