[英]Read content of text file periodically in C# app
创建一个System.Forms.Timer ,将interval设置为2分钟并处理计时器tick事件。
// Declare at form class scope
System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
// ...
myTimer.Tick += new EventHandler(TimerEventProcessor);
// Sets the timer interval to 120 seconds (2 minutes).
myTimer.Interval = 120000;
myTimer.Start();
将调用放在方法上以读取文件并将其显示在TimerEventProcessor
。
在另一个答案中提到的计时器事件中,我希望您每次都要读取该文件,即使某些其他进程当前正在锁定该文件。
但是,如果您不采取预防措施,您将在文件使用时收到异常。 当然,您可以捕获此异常,但是您需要等待几秒钟才能再次尝试。 如果文件仍然被锁定,则可能需要实现一些超时机制。
如果这不是您想要的,另一种支持读取(可能)锁定文件的方法是使用FileShare.ReadWrite参数创建的FileStream对象:
// Inside your timer event.
using (System.IO.FileStream fs = new System.IO.FileStream("yourfile.log",
System.IO.FileMode.Open, System.IO.FileAccess.Read,
System.IO.FileShare.ReadWrite))
{
// use fs to read from file as required
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.