2017-01-22 34 views
0

我正在嘗試讀取文本文件並提取其中的所有電子郵件地址。得到這個工作具有以下功能:C#在函數執行時填充進度條

我的C#功能:

public void extractMails(string filePath) 
{ 
    List<string> mailAddressList = new List<string>(); 

    string data = File.ReadAllText(filePath); 
    Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase); 
    MatchCollection emailMatches = emailRegex.Matches(data); 

    StringBuilder sb = new StringBuilder(); 

    foreach (Match emailMatch in emailMatches) 
    { 
     sb.AppendLine(emailMatch.Value); 
    } 

    string exePath = System.Reflection.Assembly.GetEntryAssembly().Location; 
    string dirPath = Path.GetDirectoryName(exePath); 

    File.WriteAllText(dirPath + "extractedEmails.txt", sb.ToString()); 
} 

現在我添加了一個進度條,因爲加載的文本文件可以是巨大的。當函數執行時,我怎麼能填充進度條,最後進度條會填充到100%?

我將不勝感激任何形式的幫助。

+0

假設的WinForms,用BackgroundWorker的 –

+1

你需要用'ReadLines'更換'ReadAllText'到逐行讀取文件中的行這對於大文件的最佳實踐,並使用async-等待模式同步執行長時間運行的代碼。 – user3185569

+0

是它的一個winform應用程序 – d45ndx

回答

0

@ user3185569評論無誤。如果您使用的是舊版本的Visual Studio,我不提供使用asyncawait的解決方案。

基本上你需要在新線程中啓動你的任務,然後用Invoke()來更新進度條。下面是一個簡單的例子:

private int _progress; 
private delegate void Delegate(); 

private void btnStartTask_Click(object sender, EventArgs e) 
{ 
    // Initialize progress bar to 0 and task a new task 
    _progress = 0; 
    progressBar1.Value = 0; 
    Task.Factory.StartNew(DoTask); 
} 

private void DoTask() 
{ 
    // Simulate a long 5 second task 
    // Obviously you'll replace this with your own task 
    for (int i = 0; i < 5; i++) 
    { 
     System.Threading.Thread.Sleep(1000); 
     _progress = (i + 1)*20; 
     if (progressBar1.InvokeRequired) 
     { 
      var myDelegate = new Delegate(UpdateProgressBar); 
      progressBar1.Invoke(myDelegate); 
     } 
     else 
     { 
      UpdateProgressBar(); 
     } 
    } 
} 

private void UpdateProgressBar() 
{ 
    progressBar1.Value = _progress; 
} 
0

您只需遍歷所需的文件中的所有對象。你需要那裏的對象數量,然後你乘以當前迭代器100除以對象的總量。 Theres你的persentage。現在用你得到的值更新酒吧的過程。