我在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 –