C#每X秒调用while循环中的函数,而不阻塞循环
我有一个C#语言的程序,我使用while循环从文件中读取行。我希望能够每隔5秒左右显示行号,而不会减慢while循环,这样用户就可以看到它们有多远。有什么办法吗 代码C#每X秒调用while循环中的函数,而不阻塞循环,c#,while-loop,nonblocking,C#,While Loop,Nonblocking,我有一个C#语言的程序,我使用while循环从文件中读取行。我希望能够每隔5秒左右显示行号,而不会减慢while循环,这样用户就可以看到它们有多远。有什么办法吗 代码 try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. Stopwatch sw = S
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);
}
}
您可以使用该类来实现这一点。只需看看MSDN示例,了解如何初始化该类
您可以使用ReportProgress调用为BackgroundWorker创建一个“DoWork”方法,如下所示:
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()。只需看看MSDN示例,了解如何初始化该类
您可以使用ReportProgress调用为BackgroundWorker创建一个“DoWork”方法,如下所示:
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()。在后台线程中运行文件读取代码并向UI线程发送通知。如果(sw.appeased.TotalSeconds%5==0)Console.WriteLine(lines+“lines read To Fast…”),则无法执行简单的
代码>在while循环中的行+++
之后工作?简单的Console.WriteLine每5秒一次不会显著降低循环速度。或者,您可以在后台线程中使用Task.run文件读取代码,并向UI线程发送通知。如果(sw.appeased.TotalSeconds%5==0)控制台无法使用简单的。WriteLine(lines+“lines read to Fast…”)代码>在while循环中的行+++
之后工作?简单的Console.WriteLine每5秒一次不会显著降低循环速度。或者您可以使用Task.runMSDN文档声明ProgressChanged事件处理程序在创建BackgroundWorker的线程上执行。DoWork应在与创建的BackgroundWorker实例不同的线程上运行。MSDN文档说明ProgressChanged事件处理程序在创建BackgroundWorker的线程上执行。DoWork应在与BackgroundWorker的创建实例不同的线程上运行。