为什么我在第二次开始下载时遇到progressBar值为104的异常?

时间:2017-01-12 08:29:28

标签: c# .net winforms

在下载按钮单击事件中,我重置progressBar2值并将min和max分别设置为0和100。在这种情况下,List newList包含9个项目。

private void btnDownload_Click(object sender, EventArgs e)
{
    btnDownload.Enabled = false;
    label7.Text = "Downloading...";
    progressBar2.Value = 0;
    progressBar2.Minimum = 0;
    progressBar2.Maximum = 100;
    downloadFile(newList);
}

然后是下载方法。

private Queue<string> _downloadUrls = new Queue<string>();

private async void downloadFile(IEnumerable<string> urls)
{
    foreach (var url in urls)
    {
        _downloadUrls.Enqueue(url);
    }

    await DownloadFile();
}

private async Task DownloadFile()
{
    if (_downloadUrls.Any())
    {
        WebClient client = new WebClient();
        client.DownloadProgressChanged += ProgressChanged;
        client.DownloadFileCompleted += Completed;

        var url = _downloadUrls.Dequeue();

        sw = Stopwatch.StartNew();
        await client.DownloadFileTaskAsync(new Uri(url), @"C:\Temp\TestingSatelliteImagesDownload\" + count + ".jpg");
        return;
    }
}

然后是progresschanged事件

private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    // Calculate download speed and output it to labelSpeed.
    label3.Text = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));

    // Update the progressbar percentage only when the value is not the same.
    double bytesInCurrentDownload = double.Parse(e.BytesReceived.ToString());
    double totalBytesCurrentDownload = double.Parse(e.TotalBytesToReceive.ToString());
    double percentageCurrentDownload = bytesInCurrentDownload / totalBytesCurrentDownload * 100;
    ProgressBar1.Value = int.Parse(Math.Truncate(percentageCurrentDownload).ToString());//e.ProgressPercentage;

    // Show the percentage on our label.
    Label4.Text = e.ProgressPercentage.ToString() + "%";

    // Update the label with how much data have been downloaded so far and the total size of the file we are currently downloading
    label10.Text = string.Format("{0} MB's / {1} MB's",
    (e.BytesReceived / 1024d / 1024d).ToString("0.00"),
    (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));

    //Let's update ProgressBar2
    double totalBytesDownloaded = e.BytesReceived + bytesFromCompletedFiles;
    double percentageTotalDownload = totalBytesDownloaded / totalBytesToDownload * 100;
    progressBar2.Value = (int)percentageTotalDownload;
    label6.Text = progressBar2.Value.ToString() + "%";
    if (progressBar2.Value == 100)
    {
        label7.Text = "Download completed";
        btnDownload.Enabled = true;
        israelDownload = true;
        totalBytesCurrentDownload = 0;
        percentageTotalDownload = 0;
        progressBar2.Value = 0;
    }
}

当progressBar2.Value为100时,我正在尝试将此处的值重置为0

已完成的活动

long bytesFromCompletedFiles = 0;
// The event that will trigger when the WebClient is completed
private async void Completed(object sender, AsyncCompletedEventArgs e)
{
     if (e.Cancelled == true)
     {
          MessageBox.Show("Download has been canceled.");
     }
     else
     {
         if (e.Error == null)
         {
              ProgressBar1.Value = 100;
              count++;
              bytesFromCompletedFiles += totalBytes[count - 1];
              label9.Text = numberoffiles--.ToString();
              await DownloadFile();
         }
         else
         {
              string error = e.UserState.ToString();
         }
     }
     sw.Stop();
}

这就是我计算totalBytesToDownload变量的方法,我正在使用这个方法助手:

long totalBytesToDownload = 0;
List<int> totalBytes;
private void getTotalBytes(List<string> urls)
{
     totalBytes = new List<int>();
     for (int i = 0; i < urls.Count(); i++)
     {
          System.Net.WebRequest req = System.Net.HttpWebRequest.Create(urls[i]);
          req.Method = "HEAD";
          using (System.Net.WebResponse resp = req.GetResponse())
          {
               int ContentLength;
               if (int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength))
               {
                    //Do something useful with ContentLength here
                        totalBytes.Add(ContentLength);
               }
           }
      }
            totalBytes.ForEach(file => totalBytesToDownload += file);
}

在backgroundworker dowork事件中使用此方法,这是在我开始下载之前:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
     ei.Init(israelDownload);
     getTotalBytes(ExtractImages.imagesUrls);
}

imagesUrls是List并包含9个项目。

我第一次点击按钮开始下载它工作正常。 一旦progressBar2值达到100%,我试图再次点击开始按钮再次下载相同的文件。在第二次我点击按钮我在第150行获得例外:

progressBar2.Value = (int)percentageTotalDownload;
  

消息=“104”的值对“值”无效。 '价值'应介于'最小'和'最大'之间。   参数名称:值          PARAMNAME =价值          来源= System.Windows.Forms的          堆栈跟踪:               在System.Windows.Forms.ProgressBar.set_Value(Int32值)               在SatelliteImages.Form1.ProgressChanged(Object sender,DownloadProgressChangedEventArgs e)

1 个答案:

答案 0 :(得分:0)

我认为问题是小数点分隔符(Cultures)。您正在使用double.Parseint.Parse。我认为你正在解析10.4' to 104 _(because in some cultures the,`是小数点分隔符。 (我在你的名字上看到你是荷兰人)你的系统可能是荷兰语._

将所有Parse更改为强制转换。

double bytesInCurrentDownload = double.Parse(e.BytesReceived.ToString());

double bytesInCurrentDownload = (double)e.BytesReceived;

此外,您正在将其格式化为en-US - &gt; e.BytesReceived / 1024d / 1024d).ToString("0.00"),

您可以查看decimal separator