gpt4 book ai didi

c# - FileSystemWatcher 更改事件(对于 "LastWrite")是不可靠的

转载 作者:太空狗 更新时间:2023-10-30 00:55:26 33 4
gpt4 key购买 nike

我正在尝试在磁盘上的文件更新时收到通知。我有兴趣在刷新发生后立即收到此通知,但是,似乎 FileSystemWatcher 只会在流打开或关闭时发送事件。

在下面的代码中,我正在写入文件并重复将缓冲区刷新到磁盘。然而,FileSystemWatcher 只在写入开始和结束时通知我一次。

还有其他方法可以获取这些通知吗?或者我应该为此使用轮询?

代码:

class Program
{
static void Main(string[] args)
{
FileSystemWatcher watcher = new FileSystemWatcher(Environment.CurrentDirectory, "Test.txt");
watcher.Changed += watcher_Changed;
watcher.EnableRaisingEvents = true;

using(TextWriter writer = new StreamWriter("Test.txt"))
{
WriteData(writer);
WriteData(writer);
WriteData(writer);
WriteData(writer);
}

Thread.Sleep(10000);
}

private static void WriteData(TextWriter writer)
{
writer.WriteLine("Hello!");
writer.Flush();
Console.WriteLine(DateTime.Now.ToString("T") + "] Wrote data");
Thread.Sleep(3000);
}

static void watcher_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine(DateTime.Now.ToString("T") + "] Watcher changed!");
}
}

更新 1

我已更正 DateTime 的 ToString 函数以显示秒数。这是上面代码的输出:

11:37:47 AM] Watcher changed!
11:37:47 AM] Wrote data
11:37:50 AM] Wrote data
11:37:53 AM] Wrote data
11:37:56 AM] Wrote data
11:37:59 AM] Watcher changed!

谢谢!

最佳答案

它与 FileSystemWatcher 无关。观察者对文件系统的 LastWrite 属性的更新作出 react 。

例如NTFS 不会在每次写入时更新 LastWrite。该值被缓存并且仅在流关闭时或在其他一些未指定的时间写入。 This document

Timestamps are updated at various times and for various reasons. The only guarantee about a file timestamp is that the file time is correctly reflected when the handle that makes the change is closed. [...] The NTFS file system delays updates to the last access time for a file by up to 1 hour after the last access

我假设类似的缓存适用于写入

关于c# - FileSystemWatcher 更改事件(对于 "LastWrite")是不可靠的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9563037/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com