后台工作者 &计时器,只读取日志文件的新行? [英] BackgroundWorker & Timer, reading only new lines of a log file?
问题描述
我的应用程序写入日志文件(当前使用 log4net).我想设置一个计时器和一个后台工作人员来读取日志文件并将其内容打印到我的表单中的某个控件中,同时它正在被写入.
My application writes a log file (currently using log4net). I'd like to setup a timer and a background worker to read the log file and print its content into some control in my form, while it's being written.
我无法使用 FileSystemWatcher 类,因为它看起来已损坏:有时已更改"事件会触发,有时不会.而且它的池化率"极低.
I can't use the FileSystemWatcher class because seems broken: sometimes the event "changed" fires, sometimes do not. And it has an extremely low "pooling rate".
所以我创建了一个 Timer 和一个 FileSystemWatcher.在计时器的滴答"事件上,后台工作人员完成其工作.
So I created a Timer and a FileSystemWatcher. On the "tick" event of the timer, the background worker does its job.
问题是:如何只读取自上次检查工人后添加的行?
The question is: how to read only the lines that are added since the last check of the worker?
public LogForm()
{
InitializeComponent();
logWatcherTimer.Start();
}
private void logWatcherTimer_Tick(object sender, EventArgs e)
{
FileInfo log = new FileInfo(@"C:log.txt");
if(!logWorker.IsBusy) logWorker.RunWorkerAsync(log);
}
private void logWorker_DoWork(object sender, DoWorkEventArgs e)
{
// Read only new lines since last check.
FileInfo log = (FileInfo) e.Argument;
// Here is the main question!
}
代码解决方案(也许有更优雅的方法?):
Code Solution (maybe there is a more elegant way?):
private void logWatherWorker_DoWork(object sender, DoWorkEventArgs e)
{
// retval
string newLines = string.Empty;
FileInfo log = (FileInfo) e.Argument;
// Just skip if log file hasn't changed
if (lastLogLength == log.Length) return;
using (StreamReader stream = new StreamReader(log.FullName))
{
// Set the position to the last log size and read
// all the content added
stream.BaseStream.Position = lastLogLength;
newLines = stream.ReadToEnd();
}
// Keep track of the previuos log length
lastLogLength = log.Length;
// Assign the result back to the worker, to be
// consumed by the form
e.Result = newLines;
}
推荐答案
每次阅读日志时检查并存储文件大小,然后在下次阅读时在该位置启动文本阅读器(或您正在使用的任何东西)阅读.
Check and store the file size each time you read the log, then start your text reader (or whatever you're using) at that location the next time you read.
这篇关于后台工作者 &计时器,只读取日志文件的新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!