【问题标题】:Updating a Label with the backgroundworker progress使用后台工作进程更新标签
【发布时间】:2015-11-11 07:57:17
【问题描述】:

我在后台工作人员的帮助下逐行读取外部 exe 的控制台,我将控制台的每一行分配给一个标签。问题是标签没有随控制台行更新。代码如下

private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    int i = 0;
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = true;
    startInfo.UseShellExecute = false;
    startInfo.FileName = EXELOCATION;
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.Arguments = Program.path;
    startInfo.RedirectStandardOutput = true;
    try
    {
        // Start the process with the info we specified.
        // Call WaitForExit and then the using statement will close.
        using (exeProcess = Process.Start(startInfo))
        {
            using (StreamReader reader = exeProcess.StandardOutput)
            {
                string result;
                while ((result = reader.ReadLine()) != null)
                {
                    // object param = result;

                    e.Result = result;
                    bgWorker.ReportProgress(i++);
                }
            }
        }
    }
    catch
    {
        // Log error.
    }
}

private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    label.Text = e.ToString();
    label.Refresh();
}

我该如何解决这个问题

【问题讨论】:

  • 你确定它没有发生吗?文件太小以至于发生得太快是偶然的吗?
  • 这是 WinForms 还是 WPF 应用程序?
  • 代码引发此错误“此 BackgroundWorker 声明它不报告进度。修改 WorkerReportsProgress 以声明它确实报告进度”。
  • 那么异常消息是否足以让您得出结论,您必须添加 bgWorker.WorkerReportsProgress = true; ?

标签: c# .net multithreading


【解决方案1】:

试试这个:

label2.Invoke(new Action(() => { label2.Text = e.ToString(); }));
label2.Invoke(new Action(() => { label2.Refresh(); }));

【讨论】:

  • @thanx 你救了我一天
【解决方案2】:

该代码可能不起作用,因为您正在尝试从非 UI 线程(也称为后台线程)更新 UI 元素。

如果您使用的是 WPF,则应使用 Dispatcher 请求在 UI 线程中更改标签。如果您使用的是其他框架,请尝试使用该框架的等效类。

在你的 ProgressChanged 方法中,试试这个:

Application.Current.Dispatcher.BeginInvoke(
  DispatcherPriority.Background,
  () => {
    label.Text = e.ToString();
  });

【讨论】:

    【解决方案3】:

    如果这是在另一个线程中(并且您在 winforms 应用程序中),您可能需要使用 Control.InvokeRequired

    public void UpdateProgress (int progress)
    {
      if (label.InvokeRequired)
      { 
         this.Invoke(()=> UpdateProgress(progress));
      }
      else
      {
         label.Text = progress.ToString();
      }
    }
    

    此方法检查它是否在 UI 线程上运行,如果不是,则在 UI 线程上调用自身。如果它已经在 UI 线程上,它只会更新标签。

    【讨论】:

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