2

我在让后台工作人员更新我的进度条时遇到了一些麻烦。我以在线教程为例,但我的代码不起作用。我在此站点上进行了一些挖掘,但找不到任何解决方案。我是后台工作人员/进度的新手。所以我不完全理解。

只是为了设置:我有一个主窗体(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

4 回答 4

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;
于 2013-07-31T21:12:55.657 回答
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));
  }
}
于 2013-07-31T21:30:58.550 回答
0

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

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

// You exit DoWork right after reporting progress

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

于 2013-07-31T21:14:20.960 回答
0

所以我做了更多的挖掘告诉对象的属性,告诉对象哪些功能没有设置:/

感谢您的帮助

于 2013-08-01T14:05:39.583 回答