gre*_*emo 11 c# log4net filesystemwatcher timer backgroundworker
我的应用程序写入一个日志文件(当前使用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!
}
Run Code Online (Sandbox Code Playgroud)
编辑:代码解决方案(也许有更优雅的方式?):
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;
}
Run Code Online (Sandbox Code Playgroud)