2013-07-31 116 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

所以,我沒有更多的挖掘 告訴,告訴目標對象的特性,這功能去沒有設置:/

感謝您的幫助