BackgroundWorker无法正常工作 [英] BackgroundWorker not working properly
问题描述
后台工作程序不起作用。仍然挂起用户界面。
甚至进度报告都没有反映在进度条中。
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 underInvoke
orBeginInvoke
. 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 theSleep
statement that blocks...) in the UI thread?Try to run only the progress change using theTry to remove theInvoke
method.Invoke
call fromDoWork
and, move the whole of the UI changes to thebackgroundWorker_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屋!