C# WinForm BackgroundWorker not Updating Processbar

本文关键字:Updating Processbar not BackgroundWorker WinForm | 更新日期: 2023-09-27 18:25:53

我在让后台工作人员更新进度条时遇到了一些小麻烦。我使用了一个在线教程作为示例,但我的代码不起作用。我在这个网站上做了一些挖掘,但找不到任何解决方案。我对幕后工作人员/进步这件事还不熟悉。所以我不完全理解。

只是为了设置:我有一个主表单(FORM1),它打开另一个带有进度条和状态标签的表单(FORM3)。

我的表3代码如下:

public string Message
{
    set { lblMessage.Text = value; }
}
public int ProgressValue
{
    set { progressBar1.Value = value; }
}
public Form3()
{
    InitializeComponent();
}

我的Form 1部分代码:

private void btnImport_Click(object sender, EventArgs e)
{
    if (backgroundWorker1.IsBusy != true)
    {
        if (MessageBox.Show("Are you sure you want to import " + cbTableNames.SelectedValue.ToString().TrimEnd('$') + " into " + _db, "Confirm to Import", MessageBoxButtons.YesNo) == DialogResult.Yes)
        {
            alert = new Form3(); //Created at beginning
            alert.Show();
            backgroundWorker1.RunWorkerAsync();
        }
    }
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    int count = 0
    foreach(DataRow row in DatatableData.Rows)
    {
    /*... Do Stuff ... */
    count++;
    double formula = count / _totalRecords;
    int percent = Convert.ToInt32(Math.Floor(formula)) * 10;
    worker.ReportProgress(percent, string.Format("Completed record {0} out of " + _totalRecords, count));
    }
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    alert.Message = (String) e.UserState;
    alert.ProgressValue = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    alert.Close();
}

所以。问题是它没有更新任何内容。进度条和标签都在更新。有人能给我指一下写作方向吗?或者有什么建议吗?

C# WinForm BackgroundWorker not Updating Processbar

这将给您0 * 10,因为count_totalRecords是整数值,这里使用整数除法。因此,count小于总记录,则formula等于0:

double formula = count / _totalRecords; // equal to 0
int percent = Convert.ToInt32(Math.Floor(formula)) * 10; // equal to 0

好吧,当所有的工作都完成时,formula等于1。但这就是进步没有改变的原因。

以下是正确的百分比计算:

int percent = count * 100 / _totalRecords;

您需要将INTEGER值强制转换为DOUBLE,否则C#数学会将其截断为0:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
  var worker = (BackgroundWorker)sender;
  for (int count = 0; count < _totalRecords; count++) {
    /*... Do Stuff ... */
    double formula = 100 * ((double)count / _totalRecords); // << NOTICE THIS CAST!
    int percent = Convert.ToInt32(formula);
    worker.ReportProgress(percent, string.Format("Completed record {0} out of " + _totalRecords, count));
  }
}

您只在工作完成之前报告进度

worker.ReportProgress(percent, string.Format("Completed record {0} out of " + _totalRecords, count));
// You exit DoWork right after reporting progress

请尝试在BackgroundWorker运行时定期报告进度。还要检查Jon的评论,以确保WorkerReportsProgress设置为true。

所以我做了更多的挖掘没有设置告诉对象的属性,这些属性告诉对象要转到哪些函数:/

感谢您的帮助