【问题标题】:Advice on Form progressbar update using backgroundWorker and async downloads使用 backgroundWorker 和异步下载更新表单进度条的建议
【发布时间】:2012-07-09 00:07:59
【问题描述】:

这是我进入异步/线程的第一步,所以提前道歉。我需要一些关于实现以下最佳方式的建议......

我有一个包含进度条的非静态窗体。我还有一个静态方法“HttpSocket”来管理异步 http 下载。因此,我无法直接从静态方法访问表单进度条。

所以我考虑使用 backgroundWorker 来运行作业。但是,由于 DoWork 也在调用异步方法,所以一旦发出所有 http 请求,backgroundWorker 就会报告完成,但我想根据接收到 http 响应和解析数据的时间来更新进度条。

我想出的一个糟糕的解决方法如下

private void buttonStartDownload_Click(object sender, EventArgs e)
{
  backgroundWorker1.RunWorkerAsync();
}

并在 backgroundWorker1_DoWork 中放置一个 while 循环来比较请求/响应

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    //Trigger Asynchronous method from LoginForm
    DataExtract LoginForm = new DataExtract();
    LoginForm.DELogin();

    //Without While Loop backgroundWorker1 completes on http requests and not responses

    // Attempt to Monitor Progress of async responses using while loop
   // HttpSocket method logs RequestCount & ResponseCount

    while (HttpSocket.UriWebResponseCount < HttpSocket.UriWebRequestCount)
    {

        if (HttpSocket.UriWebResponseCount % updateInterval == 0) 
        {
            int myIntValue = unchecked((int)HttpSocket.UriWebResponseCount / HttpSocket.UriTotal);
            backgroundWorker1.ReportProgress(myIntValue);
        }

    }

}


private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // Change the value of the ProgressBar to the BackgroundWorker progress.
    progressBar1.Value = e.ProgressPercentage;

}

但是,我意识到这不是最好的方法,因为 While 循环会影响性能并减慢通常很快但没有显示进度的异步过程。 我正在寻求有关完成此任务的正确、最有效方法的建议,或者提供替代方法来使用 C#4.0 使用或不使用 BackgroundWorker 从单独的异步线程更新表单进度条?

谢谢

【问题讨论】:

    标签: c# asynchronous progress-bar backgroundworker


    【解决方案1】:

    在不完全了解您的请求/响应模型的架构的情况下,后台工作程序中的 while 循环看起来好像在忙于等待。

    您可以通过在 while 循环的顶部插入睡眠操作来减少检查进度状态的频率,我还建议在报告进度之前取消检查以查看响应计数是否为整数值。

    while (HttpSocket.UriWebResponseCount < HttpSocket.UriWebRequestCount) 
    { 
        Thread.Sleep(250); // sleep for 250 ms before the next check
    
        int myIntValue = (int)Math.Floor((double)HttpSocket.UriWebResponseCount / HttpSocket.UriTotal); 
        backgroundWorker1.ReportProgress(myIntValue); 
    } 
    

    希望静态属性 HttpSocket.UriWebResponseCount 和 HttpSocket.UriWebRequestCount 正在以线程安全的方式更新和读取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多