C#后台工作者更新状态标签

Teh*_*Guy 7 c# label backgroundworker winforms

这应该是一件相当简单的事情; 但是,我一直无法弄清楚这一点.

/// This section is located in the InitializeComponent() method
/// form's class, i.e. partial class frmMain { .... }
this.bgw = new System.ComponentModel.BackgroundWorker();
this.bgw.WorkerReportsProgress = true;
this.bgw.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bgw_DoWork);
this.bgw.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.bgw_ProgressChanged);

/// This code is located in public partial class frmMain : Form { .... }
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
    for (int i = 1; i <= 100; i++)
    {
        Thread.Sleep(100); // Wait 100 milliseconds
        //Console.WriteLine(i);
        bgw.ReportProgress(i);
    }
}
private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    // Update status label
    lblStatus.Text = e.ProgressPercentage.ToString();
}
// New code added to question after edit
public frmMain()
{
    InitializeComponent();
    bgw.RunWorkerAsync();
    // some more stuff...
}
Run Code Online (Sandbox Code Playgroud)

后台工作者正常运行; 但是,它没有正确更新其进度.如果我取消注释DoWork事件中的注释行,我能够正确地看到状态更新; 但是,在主线程中的任务(繁重的数据库计算内容)完成之后,才会触发ProgressChanged事件.

这是使用.NET Framework 4并且是Windows窗体应用程序.

编辑

请参阅上面代码中的注释,了解代码所在的位置.

更多细节

正在执行的代码涉及在数据库上执行多个查询.我无权披露该代码.至于如何执行代码,我实际上不知道,因为我被另一个开发人员交给了.dll并被告知只在访问数据库时才使用它....

编辑

"更多东西"部分中的代码被移动如下

private void frmMain_Load(object sender, EventArgs e)
{
   // some more stuff... aka run queries!
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*rvy 4

你的BackgroundWorker代码很好。问题在于您在其他地方(在本例中为构造函数或FormLoad)中的代码阻塞了 UI 线程(通过执行同步数据库请求)。您需要做一些事情来确保此代码在非 UI 线程中运行。这可能意味着使用现有的任务BackgroundWorker来执行其他长时间运行的任务;也可以通过使用Task.Factory.StartNew或其他一些线程机制使其在非 UI 线程中运行来完成。

一旦 UI 线程没有被阻止,您将看到在 UI 中反映的 `ProgressChanged 事件处理程序中所做的更新。