2017-10-04 71 views
0

我在C#中有一個程序,我使用while循環從文件中讀取行。我希望能夠每隔5秒左右顯示行號,而不減慢while循環,這樣用戶就可以看到它們有多遠。任何想法如何做到這一點?C#在while循環中調用函數每X秒沒有阻塞循環

CODE

try 
    { 
     // Create an instance of StreamReader to read from a file. 
     // The using statement also closes the StreamReader. 
     Stopwatch sw = Stopwatch.StartNew(); 
     using (StreamReader sr = new StreamReader(@"C:\wamp64\www\brute-force\files\antipublic.txt")) 
     { 
      String line; 
      int lines = 0; 
      // Read and display lines from the file until the end of 
      // the file is reached. 
      using (System.IO.StreamWriter file = new System.IO.StreamWriter("C:/users/morgan/desktop/hash_table.txt")) 
      { 
       while ((line = sr.ReadLine()) != null) 
       { 
        file.WriteLine(CreateMD5(line)+':'+line); 
        lines++; 
       } 
      } 
     } 

     sw.Stop(); 
     Console.WriteLine("Time taken: {0}s", sw.Elapsed.TotalSeconds); 
     Console.ReadLine(); 
    } 
    catch (Exception e) 
    { 
     // Let the user know what went wrong. 
     Console.WriteLine("The file could not be read:"); 
     Console.WriteLine(e.Message); 
    } 
} 
+0

在後臺線程中運行文件讀取代碼並向UI線程發送通知。 –

+1

不能在你的while循環中的'++ ++'之後使用一個簡單的'if(sw.Elapsed.TotalSeconds%5 == 0)Console.WriteLine(lines +「行讀到目前爲止...」);'' –

+1

簡單的Console.WriteLine每5秒鐘不會顯着減慢循環。或者您可以使用Task.Run –

回答

3

可以使用BackgroundWorker類來實現這一目標。只要看MSDN的例子就可以瞭解如何初學這門課。

您可以爲BackgroundWorker的一個「DoWork的」方法與ReportProgress調用是這樣的:

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) 
{ 
    BackgroundWorker worker = sender as BackgroundWorker; 

    Stopwatch sw = Stopwatch.StartNew(); 
    using (StreamReader sr = new StreamReader(@"path")) 
    { 
     String line; 
     int lines = 0; 

     using (System.IO.StreamWriter file = new System.IO.StreamWriter("path")) 
     { 
      while ((line = sr.ReadLine()) != null) 
      { 
       file.WriteLine(CreateMD5(line)+':'+line); 
       worker.ReportProgress(lines++); 
      } 
     } 
    } 
} 

要顯示在ProgressChanged事件你只需我們可以使用Console.WriteLine進度()。

+0

MSDN文檔指出ProgressChanged事件處理程序在創建BackgroundWorker的線程上執行。 DoWork應該在與BackgroundWorker的創建實例不同的線程上運行。 – Shamshiel