擅长:python、mysql、java
<p>尽管<code>FileSystemWatcher</code>是最简单的解决方案,但我发现它在现实中是不可靠的。。通常,可以用新内容更新文件,但是<code>FileSystemWatcher</code>直到几秒钟后才会触发事件,而且通常永远不会。</p>
<p>我发现唯一可靠的方法是使用<code>System.Timers.Timer</code>对象定期检查对文件的更改并检查文件大小。</p>
<p>我在这里写了一个小类来演示这一点:</p>
<p><a href="https://gist.github.com/ant-fx/989dd86a1ace38a9ac58" rel="noreferrer">https://gist.github.com/ant-fx/989dd86a1ace38a9ac58</a></p>
<p><strong>示例用法</strong></p>
<pre><code>var monitor = new LogFileMonitor("c:\temp\app.log", "\r\n");
monitor.OnLine += (s, e) =>
{
// WARNING.. this will be a different thread...
Console.WriteLine(e.Line);
};
monitor.Start();
</code></pre>
<p>这里唯一真正的缺点(除了文件大小检查导致的轻微性能延迟外)是因为它使用了<code>System.Timers.Timer</code>回调来自不同的线程。</p>
<p>如果您使用的是Windows窗体或WPF应用程序,则可以轻松地修改类以接受<code>SynchronizingObject</code>,这将确保从同一线程调用事件处理程序事件。</p>