【问题标题】:C# backgroundWorker reports string?C# backgroundWorker 报告字符串?
【发布时间】:2009-08-17 17:30:35
【问题描述】:

如何从 backgroundWorker 以及百分比向我的 windows.form 报告字符串(如“正在搜索文件......”、“找到的选择......”)。此外,我有一个大类,其中包含我想在 backgroundWorker_Work 中运行的方法。我可以通过 Class_method() 调用它;但我无法报告我完成的百分比或来自被调用类的任何内容,只能来自 backgroundWorker_Work 方法。

谢谢!

【问题讨论】:

    标签: c# visual-studio-2008 reporting backgroundworker progress


    【解决方案1】:

    我假设 WCF 也有这个方法

    public void ReportProgress(int percentProgress, Object userState); 
    

    所以只需使用userState来报告字符串。

    private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
     //report some progress
     e.ReportProgress(0,"Initiating countdown");
    
    // initate the countdown.
    }
    

    您将在 ProgressChanged 事件中返回“启动倒计时”字符串

    private void worker_ProgressChanged(object sender,ProgressChangedEventArgs e) 
    {
      statusLabel.Text = e.UserState as String;
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用ReportProgress 方法的userState 参数来报告该字符串。

      这是一个来自 MSDN 的示例:

      private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
      {
          // This method will run on a thread other than the UI thread.
          // Be sure not to manipulate any Windows Forms controls created
          // on the UI thread from this method.
          backgroundWorker.ReportProgress(0, "Working...");
          Decimal lastlast = 0;
          Decimal last = 1;
          Decimal current;
          if (requestedCount >= 1)
          { AppendNumber(0); }
          if (requestedCount >= 2)
          { AppendNumber(1); }
          for (int i = 2; i < requestedCount; ++i)
          {
              // Calculate the number.
              checked { current = lastlast + last; }
              // Introduce some delay to simulate a more complicated calculation.
              System.Threading.Thread.Sleep(100);
              AppendNumber(current);
              backgroundWorker.ReportProgress((100 * i) / requestedCount, "Working...");
              // Get ready for the next iteration.
              lastlast = last;
              last = current;
          }
      
          backgroundWorker.ReportProgress(100, "Complete!");
      }
      

      【讨论】:

        【解决方案3】:

        阅读Simple Multi-threading in Windows Forms

        这是一个由 3 部分组成的系列。

        【讨论】:

          【解决方案4】:

          使用委托。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-01-18
            • 2016-09-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多