2015-09-01 146 views
-1

我有一個方法getPlugins需要相當長的時間才能運行。本質上它解析了一個非常大的日誌文件。我知道日誌文件從時間0到時間24.我想根據當前時間更新ProgressBar。這裏是我的代碼的結構,但只有當我的循環完成後,條纔會更新......我該如何解決這個問題?更新循環中的進度欄​​

private void getPlugins(String filePath) 
{ 
    var w = new Window2(); 
    w.Show(); 
    w.progress.Value = 0; 

    List<String> pluginNames = new List<String>(); 

    string strLine; 

    // Read the file and display it line by line. 
    System.IO.StreamReader file = new System.IO.StreamReader(filePath); 

     while ((strLine = file.ReadLine()) != null) 
     { 
      // Do stuff.... 

      float time; // Here I have time as a float from 0 to 24 
      w.progress.Value = time; 
     } 

     file.Close(); 
     w.progress.Value = 24; 
     w.Close(); 
} 
+2

出現這種情況的原因是因爲你的努力更新和處理在UI線程上的文件。您需要創建一個線程來處理該文件,然後看到如何更新進度條以下內容http://stackoverflow.com/questions/6036279/wpf-progress-bar-update-with-dispatcher – 3dd

+1

請參閱此鏈接](http://stackoverflow.com/questions/12676490/progress-bar-not-progressing)和[this](http://www.dotnetcurry.com/ShowArticle.aspx?ID=571)調度員和後臺工作者。 – learningNew

+0

http://stackoverflow.com/questions/6365887/can-you-link-to-a-good-example-of-using-backgroundworker-without-placing-it-on-a/6365951#6365951 – CharithJ

回答

1

基本上這個想法是,你不能直接從非UI線程更新UI元素。 WPF有一個Dispatcher類,插上U訪問UI元素,並使用此您可以更新喜歡的UI元素下面的代碼

Application.Current.Dispatcher.Invoke(DispatcherPriority.ApplicationIdle, (Action)(() => 
        { 
         w.progress.Value = time; 
        })); 
+0

@wudzik OP ??在這裏沒有看到任何其他代碼。 – WAQ