2014-08-31 43 views
1

傳遞函數的進度幾天前,我已經問了一個關於how to constantly check the progress of a function的問題,但我還沒有收到任何答案,所以我試圖找到一種方法來做到這一點,所以我做了在我的函數ref參數,他們還給我要處理的項目總數和當前處理項目

最好是通過參考值

public void SaveInfoToDBFromFiles(string path,ref int TotalItems, ref int CurrentItem) 
{ 
    initialize the values; 
    do some stuff; 

    TotalItems=TotalNumberOfFiles; 

    foreach(file in path) 
    { 
    CurrentItem++; 
    } 
} 

,並在我的UI,的WinForms,我讓一個線程我有一個進度條,顯示了我函數的當前進度和通過獲取CurrentItem值來更新進度條的計時器,

 System.Threading.Thread th = new System.Threading.Thread(() => SaveInfoToDBFromFiles(path,ref Total,ref Current)); 

     th.Start(); 
     progressBar1.Value=Total; 
     timer1.Start(); 


private void timer1_Tick(object sender, EventArgs e) 
    { 
     progressBar1.Value = Current; 
    } 

它完美,但即時知道是否是好主意或沒有?

+0

我認爲不是 - 基本上 - 這不是一個線程安全的解決方案。 – 2014-08-31 11:56:13

回答

4

你可以這樣做 - 我認爲 - 現在是一種更好的方式。

您可以使用Progress<T>類,並讓該框架將其封送回您的UI線程。

有點像這樣:

var progress = new Progress<int>(currentItem => 
{ 
    progressBar1.Value = currentItem; 
}); 

await Task.Run(() => SaveInfoToDBFromFiles(path, progress); 

然後,你可以只報告在保存方法的進展:

public void SaveInfoToDBFromFiles(string path, IProgress<int> progress) { 
    // .. other code here .. 
    var i = 0; 

    foreach (var file in path) { 
     progress.Report(i); 
     i++; 
    } 
} 

你甚至可以換行擁有更多的信息,自定義類型:

// first, a class to hold it all 
class MyType { 
    public string FileName { get; set; } 
    public int CurrentItem { get; set; } 
} 

// .. then you need to declare the Progress instance to hold your type 

var progress = new Progress<MyType>(myType => 
{ 
    label1.Text = myType.FileName; 
    progressBar1.Value = myType.CurrentItem; 
}); 

// then when you're reporting progress you pass an instance of your type 
progress.Report(new MyType { 
    FileName = file, 
    CurrentItem = i 
}); 
+0

不錯的主意,但我怎麼能得到的項目總數?我不想在UI中獲得它。 – Behzad 2014-08-31 12:13:29

+0

好的這個問題我出來一個想法,我可以報告的百分比,所以我不需要擔心項目的總數,但我怎麼能將當前處理文件名稱傳遞到用戶界面? – Behzad 2014-08-31 12:15:04

+0

'進度'接受任何東西 - 我的例子只是一個'int'。你可以創建你自己的自定義類型,可以保存任何你想要的。例如,它可以將您從方法報告回來的「Total」,「Current」,「Percent」和「FileName」值保存回UI。 – 2014-08-31 12:15:06