我正在使用
FileSystemWatcher
来监视多个文件夹中新添加的文件。 FileSystemWatcher
是为N个文件夹/目录创建的,以便分别观看。它在开始时工作正常,但一段时间后它不会引发任何事件。我在这里错过了什么吗?非常感谢任何意见/帮助。
// Set up FileSystemWatchers for the specific subdirectories.
foreach (string subdirectory in subdirectoriesToWatch)
{
string subdirectoryPath = Path.Combine(rootDirectory, subdirectory);
FileSystemWatcher subdirectoryWatcher = CreateWatcher(subdirectoryPath, true);
subdirectoryWatcher.Created += (sender, e) =>
{
Console.WriteLine($"File created in {subdirectory}: {e.Name}");
};
}
我还增加了
InternalBufferSize
,它将根据提供的文件掩码来过滤属性。
FileSystemWatcher
实例由于其在 for 循环内的内部作用域而被垃圾收集。更改您的代码以使用 GC.KeepAlive()
:
// assumes this is in scope for the duration of your code; declare at program level if required....
var l = new List<FileSystemWatcher>();
foreach (string subdirectory in subdirectoriesToWatch)
{
string subdirectoryPath = Path.Combine(rootDirectory, subdirectory);
FileSystemWatcher subdirectoryWatcher = CreateWatcher(subdirectoryPath, true);
GC.KeepAlive(subdirectoryWatcher);
l.Add(subdirectoryWatcher);
subdirectoryWatcher.Created += (sender, e) =>
{
Console.WriteLine($"File created in {subdirectory}: {e.Name}");
};
}