我在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);
}
}
在後臺線程中運行文件讀取代碼並向UI線程發送通知。 –
不能在你的while循環中的'++ ++'之後使用一個簡單的'if(sw.Elapsed.TotalSeconds%5 == 0)Console.WriteLine(lines +「行讀到目前爲止...」);'' –
簡單的Console.WriteLine每5秒鐘不會顯着減慢循環。或者您可以使用Task.Run –