2013-01-08 40 views
0

我有一個長時間運行的 - 每個循環,並想知道是否有一種慣用的方式來添加一些視覺用戶反饋,所以用戶不認爲應用程序崩潰。對長時間運行的任務的視覺反饋

private void btnRunLongRunningTask_Click(object sender, EventArgs e) 
{ 
    foreach(string path in Directory.EnumerateFiles(@"path"), "*.ext", SearchOption.AllDirectories)) 
    { 
     var result = LongRunning.Task(path); 
     string resultPath = Manipulate(path); 
     // write result to resultPath 
    } 
} 

這可能有助於:它不是很多,任務本身需要很長時間,但可能會有很多。

我如何能做到這一點有什麼建議?由於我給了一個目錄作爲參數,我想我會查找執行任務的次數,然後相應地更新進度條,在後臺工作中運行任務和更新代碼,注意交叉訪問的問題。

+0

進度條?每次迭代後,您都會進入進度條。 – Botonomous

+0

看看使用後臺工作人員 - http://stackoverflow.com/questions/7546222/adding-a-progress-bar – MethodMan

+0

這似乎是可能使用[TPL](http://msdn.microsoft.com/zh-cn/ com/en-us/library/dd460717.aspx),特別是[Parallel.Foreach](http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.foreach.aspx)(so只要LongRunning.Task是線程安全的),這可能會更快。我從來沒有用過WinForms,所以我不知道你是否可以直接調用它,或者如果你在BackgroundWorker中調用Parallel.Foreach(或[TaskFactory.StartNew](http://msdn.microsoft.com/) .com/en-us/library/dd321439.aspx),這更簡單)。 – gregmac

回答

4

您可以將工作轉移到一個BackgroundWorker,使用ReportProgress方法。

for (i = 0; i < count; i++) 
{ 
    // do work 
    worker.ReportProgress((100 * i)/count); 
} 

private void MyWorker_ProgressChanged(object sender, 
    ProgressChangedEventArgs e) 
{ 
    taskProgressBar.Value = Math.Min(e.ProgressPercentage, 100); 
} 
+2

+1'BackgroundWorker'對於線程新手來說可能更容易實現。 –