【发布时间】:2011-05-18 03:26:21
【问题描述】:
我的应用程序写入一个日志文件(当前使用 log4net)。我想设置一个计时器和一个后台工作人员来读取日志文件并将其内容打印到我的表单中的某个控件中,同时它正在被写入。
我不能使用 FileSystemWatcher 类,因为它似乎坏了:有时“更改”事件会触发,有时不会。而且它的“池化率”极低。
所以我创建了一个 Timer 和一个 FileSystemWatcher。在计时器的“tick”事件中,后台工作人员完成其工作。
问题是:如何只读取自上次检查工人以来添加的行?
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!
}
编辑:代码解决方案(也许有更优雅的方法?):
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;
}
【问题讨论】:
标签: c# timer log4net backgroundworker filesystemwatcher