BackgroundWorker无法正常工作 [英] BackgroundWorker not working properly

查看:88
本文介绍了BackgroundWorker无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

后台工作程序不起作用。仍然挂起用户界面。



甚至进度报告都没有反映在进度条中。



Background Worker doesn't work. still hangs the UI.

Even Progress report doesn't reflect in progress bar.

private void cmdStartUtility_Click(object sender, EventArgs e)
       {
          backgroundWorker.RunWorkerAsync();
       }







private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
       {

           this.Invoke(new Action(() =>
           {

               for (int i = 0; i < 100;i++ )
               {
                   Thread.Sleep(1000);
                   backgroundWorker.ReportProgress(i);
                   txtLog.Text = i.ToString();
               }

                   backgroundWorker.ReportProgress(100);
           }));
       }







private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
       {
           progressBar1.Value = e.ProgressPercentage;
       }

推荐答案

我很久没见过这么多荒谬了。您创建一个单独的线程,然后将其所有代码调回UI线程。在非UI线程上执行的所有代码不应位于 Invoke BeginInvoke 下。你应该只在一些快速执行的动作中使用这些方法,这些动作对UI有所帮助。



请参阅我的过去的答案和我在这一篇中引用的其他答案:主线程上的.NET事件 [ ^ ]。



-SA
I haven't seen so much of absurd for a long time. You create a separate thread and then invoke all its code back to the UI thread. All code executed on the non-UI thread should not be under Invoke or BeginInvoke. You should use these methods only in some quickly executed actions which do something to the UI.

Please see my past answer and my other answers referenced in this one: .NET event on main thread[^].

—SA


我猜你使用的是WinForms。 Invoke 方法允许您在UI线程中运行代码。但是,为什么要在UI线程中运行整个worker的代码(包括阻止......的 Sleep 语句)? 尝试使用调用方法仅运行进度更改。尝试删除调用 DoWork 调用,并将整个UI更改移动到 backgroundWorker_ProgressChanged 方法(请参阅下面的注释)。类似于:

I guess you work with WinForms. The Invoke method lets you to run code in the UI thread. But, why do you run the whole of the worker's code (including the Sleep statement that blocks...) in the UI thread? Try to run only the progress change using the Invoke method. Try to remove the Invoke call from DoWork and, move the whole of the UI changes to the backgroundWorker_ProgressChanged method (see the comment below). Something like:

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
       {
               for (int i = 0; i < 100;i++ )
               {
                   Thread.Sleep(1000);
                   backgroundWorker.ReportProgress(i);                   
               }
 
               backgroundWorker.ReportProgress(100);
       }

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
       {
           txtLog.Text = e.ProgressPercentage.ToString();
           progressBar1.Value = e.ProgressPercentage;
       }


这篇关于BackgroundWorker无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆