使用计时器延迟逐行readline方法C# [英] Using a timer to delay a line by line readline method C#
问题描述
我正在使用Visual Studio 2010使用C#Windows窗体.不要让控制台部分使您感到困惑,它是用户定义的东西,而不是实际的控制台.因此,我有一种逐行打印文件的方法.我必须使它看起来打印缓慢,所以我目前正在使用Thread.Sleep来减慢逐行打印的速度.我不能使用它,因为它冻结了程序中的其他一些组件.我希望看看是否可以使用计时器来代替.虽然我看到的所有与计时器一起使用的示例通常都有一个由计时器调用的方法.方法中间没有计时器延迟.因此,我不确定如何在此处使用计时器.
I am using C# Windows Forms using Visual Studio 2010. Don't let the Console part confuse you it's a user defined thing not the actual console. So I have a method that prints a file line by line. I have to make it appear to print slowly so I am currently using Thread.Sleep to slow the line by line printing. I cannot use this because it freezes up some other components in the program. I was hoping to see if this could be done with a timer instead. Though all the examples I see being used with a timer generally have a method being called by the timer. Not have a timer delay in the middle of a method. So I'm not sure how I can go about using a timer here.
public void SlowPrint(string FileName)
{
string line;
string tempFileName;
string MyFilesDir = "..\\..\\myFolder\\";
tempFileName = Path.Combine(MyFilesDir, FileName);
if (System.IO.File.Exists(tempFileName))
{
System.IO.StreamReader file = new System.IO.StreamReader(tempFileName);
while (((line = file.ReadLine()) != null))
{
Console.WriteLine(line);
System.Threading.Thread.Sleep(700); //This has to go
}
file.Close();
}
else
{
Console.WriteLine("Error " + tempFileName + " does not exists");
}
Console.ReadLine();
}//end SlowPrint method
推荐答案
等待 Task.Delay
与 File.ReadLines
结合起来使此操作非常容易:>
awaiting Task.Delay
makes this operation quite easy, in combination with File.ReadLines
:
public async Task SlowPrint(string fileName)
{
//TODO stuff to generate real file path and check if it exists
foreach(var line in File.ReadLines(fileName))
{
Console.WriteLine(line);
await Task.Delay(700);
}
}
C#5.0之前的解决方案较难,但肯定可以实现.只需创建一个计时器并在每次触发时读取新行即可:
A pre C# 5.0 solution is harder, but certainly possible. Just create a timer and read a new line whenever it fires:
public void SlowPrint(string FileName)
{
var iterator = File.ReadLines(FileName).GetEnumerator();
System.Threading.Timer timer = null;
timer = new System.Threading.Timer(o =>
{
if (iterator.MoveNext())
Console.WriteLine(iterator.Current);
else
{
iterator.Dispose();
timer.Dispose();
}
}, null, 700, Timeout.Infinite);
}
这篇关于使用计时器延迟逐行readline方法C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!