C#在while循环中调用函数每X秒没有阻塞循环
问题描述:
我在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);
}
}
答
可以使用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
在后台线程中运行文件读取代码并向UI线程发送通知。 –
不能在你的while循环中的'++ ++'之后使用一个简单的'if(sw.Elapsed.TotalSeconds%5 == 0)Console.WriteLine(lines +“行读到目前为止...”);'' –
简单的Console.WriteLine每5秒钟不会显着减慢循环。或者您可以使用Task.Run –