C#WinForm BackgroundWorker未更新进度条

时间:2013-07-31 21:07:59

标签: c# winforms backgroundworker

我在让后台工作人员更新我的进度条方面遇到了一些麻烦。我在网上使用教程作为例子,但我的代码不起作用。我在这个网站上做了一些挖掘,我找不到任何解决方案。我是背景工作/进步的新手。所以我不完全理解。

只是为了设置: 我有一个主窗体(FORM 1)打开另一个(FORM 3),带有进度条和状态标签。

我的表格3代码原样:

public string Message
{
    set { lblMessage.Text = value; }
}

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

我的表格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();
}

因此。问题是它没有更新任何东西。进度条和标签正在更新。有人能指出我的写作方向还是有建议?

4 个答案:

答案 0 :(得分:3)

这会给你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;

答案 1 :(得分:1)

您需要将INTEGER值转换为DOUBLE,否则C#Math会将其截断为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));
  }
}

答案 2 :(得分:0)

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

worker.ReportProgress(percent, string.Format("Completed record {0} out of " + _totalRecords, count));

// You exit DoWork right after reporting progress

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

答案 3 :(得分:0)

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

感谢您的帮助