FileSystemWatcher 一段时间后停止引发事件[重复]

问题描述 投票:0回答:1

我正在使用

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
,它将根据提供的文件掩码来过滤属性。

c# filesystemwatcher
1个回答
-1
投票

这是因为您的

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}");
    };
}
© www.soinside.com 2019 - 2024. All rights reserved.