2015-10-05 49 views
0

我正在處理一個包含超過10,000行的文件並將其存儲在數據庫中。處理文件通常需要2-3分鐘,所以我想顯示progressbar進度條在winform中凍結

問題的方案是,我progressbar控制以及label這是在processForm不顯示在所有。我搜索了幾個小時,但仍然無法解決它。

enter image description here

這裏是我的代碼 btnApplyEOD_Click方法,處理

private void btnApplyEOD_Click(object sender, EventArgs e) 
{ 
    string url = txtEODReport.Text; 
    if (url != null) 
    { 
     using (var file = new System.IO.StreamReader(url)) 
     { 
      int i = 0; 
      linesInEOD = File.ReadAllLines(url).Count(); 

      if (backgroundWorkerEOD.IsBusy != true) 
      { 
       progressForm = new ProgressForm(); 
       progressForm.Show(); 
       backgroundWorkerEOD.RunWorkerAsync(); 
      } 

      while ((line = file.ReadLine()) != null) 
      { 
       string[] splitLines = line.Split('~'); 
       switch (splitLines[0]) 
       { 
        case "01": 
        { 
         BOID = splitLines[1].Trim() + splitLines[2].Trim(); 
         break; 
        } 
        ......... 
       } 
       i++; 
       currentLine = i; 
      } 
     } 
     ........... 
     bindToGridView(); 
    } 

} 

我用BackgroundWorker和代碼BackgroundWorker_DoWork方法的文件如下:

private void backgroundWorkerEOD_DoWork(object sender, DoWorkEventArgs e) 
{ 
    BackgroundWorker workerEOD = sender as BackgroundWorker; 
    //for (int i = 1; i <= 10; i++)    //usually works but useless for this scenario 
    //{ 
    // workerEOD.ReportProgress(i * 10); 
    // System.Threading.Thread.Sleep(500); 
    //} 

    for (int i = 1; i <= linesInEOD; i++)  // doesn't work at all but it will give accurate progressbar increase 
    { 
     workerEOD.ReportProgress(100 * currentLine/linesInEOD); 
    } 
} 

BackgroundWorker_ProgressChanged方法:

private void backgroundWorkerEOD_ProgressChanged(object sender, ProgressChangedEventArgs e) 
{ 
    progressForm.Message = "In progress, please wait... " + e.ProgressPercentage.ToString() + "%"; 
    progressForm.ProgressValue = e.ProgressPercentage; 
} 
+3

您應該在'DoWork'方法中移動處理。目前你的後臺工作人員什麼都不做,因爲所有的處理都在UI線程上。 –

+0

@IvanStoev:是的,這是問題所在。謝謝.. – TFrost

回答

3

您正在UI線程中執行耗時的任務,因此凍結UI是正常的。我想你應該把你的耗時任務的BackgroundWorkerDoWork和呼叫backgroundWorker1.RunWorkerAsync();當你需要:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
{ 
    this.PerformTimeConsumingTask(); 
} 

public void PerformTimeConsumingTask() 
{ 
    //Time-Consuming Task 

    //When you need to update UI 
    progressForm.Invoke(new Action(() => 
    { 
     progressForm.ProgressValue = someValue; 
    })); 
} 

如果您使用的是.NET 4.5,你也可以考慮使用async/await模式。

+0

我做錯了,而不是將處理任務分配給'backgroundWorkerEOD_DoWork',我將進度條任務分配給'DoWork'。這是我第一次在'WinForms'和'progressbar'中,所以我不知道我做錯了什麼。感謝您指出問題。 – TFrost

+0

不客氣:)你可能會發現我的描述[這裏](http://stackoverflow.com/a/32620833/3110834)也有幫助。 –