2013-07-31 111 views
2

我在获取backgroundworker更新我的进度条时遇到了一些问题。我正在使用在线教程作为示例,但我的代码无法正常工作。我在这个网站上做了一些挖掘,找不到任何解决方案。我是背景工作者/进步的新手。所以我不完全理解它。C#WinForm 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(); 
} 

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

+2

您是否设置了'BackgroundWorker.WorkerReportsProgress'? –

+1

DoWork内部的代码在while循环中,对吗?不要简化太多。 –

回答

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; 
+0

我会尝试,让你们知道..谢谢你的建议... –

0

工作完成

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

// You exit DoWork right after reporting progress 

尝试定期报告进展情况,而BackgroundWorker的运行之前你只报告进度。同时检查Jon的评论以确保WorkerReportsProgress设置为true。

1

您需要将整数值转换为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)); 
    } 
} 
0

所以,我没有更多的挖掘 告诉,告诉目标对象的特性,这功能去没有设置:/

感谢您的帮助