2011-09-14 37 views
0

我在我的應用程序下面的代碼:更新UI使用定時器每1秒在C#

Task.Factory.StartNew(() => 
{ 
    progressReporter.ReportProgress(() => 
    { 
     stopWatch.Start(); 
     lblStatus.Text = "We've begun!"; 
    }); 

    int c = 0; 

    DateTime starttime = DateTime.Now; 

    foreach (string file in fileList) 
    { 
     c++; 
     csvCreator.createCSV(file); 

     progressReporter.ReportProgress(() => 
     { 
      //Estimated time remaining 
      if (c % 100 == 0) 
      { 
       TimeSpan timespent = DateTime.Now - starttime; 
       int secondsremaining = (int)(timespent.TotalSeconds/c * (total - c)); 
       TimeSpan t = TimeSpan.FromSeconds(secondsremaining); 
       lblTimeRemaining.Text = string.Format("{0:D2}h:{1:D2}m:{2:D2}s", 
       t.Hours, 
       t.Minutes, 
       t.Seconds, 
       t.Milliseconds); 
      } 

      //Progress bar        
      int percentComplete = (c * 100/total); 
      if ((int)percentComplete <= progressBar.Maximum) 
      { 
       progressBar.Value = (int)percentComplete; 
      } 
     } 

    });  
} 

現在,我的代碼檢查每第100次迭代和更新UI。我寧願每隔一秒檢查一次,以提供更好的用戶體驗。

任何想法,我會如何做到這一點?

+4

創建1秒的間隔定時器,每次蜱時間更新UI。你已經知道解決方案。但是你真正的問題可能是你在主線程中有一個耗時的任務。你需要在後臺線程中,並且UI更新需要被調用到UI線程上。 –

+0

謝謝。我正在尋找在我現有代碼的上下文中使用Timer對象的具體實現。 createCSV是一個處理器密集型任務,但它確實在後臺線程上運行,並且ProgressReporter類允許我訪問UI線程以更新UI,保持一切美好而新鮮。 –

+0

只需創建一個計時器,設置它的屬性,添加一個事件處理程序,你就可以走了。這裏的所有都是它的。 –

回答

0

而不是if (c%100==0),查找您的stopWatch:它達到1秒?如果是 - >更新ui。

當然,每次UI更新後重置stopWatch

這就是說,請注意更新UI需要消息循環運行。如果UI線程停留在文件處理循環中,那麼您的UI將無法正確更新。