我的应用程序写入一个日志文件(目前使用log4net)。我想设置一个计时器和一个后台工作来读取日志文件,并在写入时将其内容打印到表单中的某个控件中。BackgroundWorker&Timer,仅读取日志文件的新行?
我不能使用FileSystemWatcher类,因为看起来有些破碎:有时事件“改变”会触发,有时不会。它具有极低的“汇集率”。
所以我创建了一个Timer和一个FileSystemWatcher。在计时器的“滴答”事件中,后台工作人员完成其工作。
现在的问题是:如何只读取自上次检查工作人员后添加的行?
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;
}
我选择了你的方式,非常感谢。我编辑了第一篇文章以包含代码解决方案。 – gremo 2010-11-30 22:06:06
非常感谢发布解决方案 – 2013-06-19 11:18:05