使用FileSystemWatcher,是否有办法在事件触发后处理事件侦听器的实例?
我的程序基本上是在新创建的文件夹中监听batch.complete.xml文件的创建。一旦程序检测到文件已经创建,就不需要继续监听该文件夹了。
我的程序如下:
public static void watchxmlfile(batchfolderpath){
var deliverycompletewatcher = new FileSystemWatcher();
deliverycompletewatcher.Path = batchfolderpath;
deliverycompletewatcher.Filter = "*.xml";
deliverycompletewatcher.Created += new FileSystemEventHandler(OnChanged);
deliverycompletewatcher.EnableRaisingEvents = true;
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
BuildingestionXml(string.Format(@"{0}\{1}",e.FullPath,e.Name));
Console.WriteLine(@"Second: Success sending{0}\{1}", e.FullPath, e.Name);
}
因此,当上述事件被触发时,我不再需要在“batchfolderpath”中监视事件,除非显式调用watchxmlfile(),它将有一个新路径。
我正在尝试防止上述事件的过多侦听器实例的内存泄漏。
答案 0 :(得分:5)
在你EventHandler
中,您可以取消分配事件,但您必须将FileSystemWatcher
声明为变量。
实施例
private static FileSystemWatcher deliverycompletewatcher;
public static void watchxmlfile(string batchfolderpath)
{
deliverycompletewatcher = new FileSystemWatcher();
deliverycompletewatcher.Path = batchfolderpath;
deliverycompletewatcher.Filter = "*.xml";
deliverycompletewatcher.Created += OnChanged;
deliverycompletewatcher.EnableRaisingEvents = true;
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
deliverycompletewatcher.EnableRaisingEvents = false;
deliverycompletewatcher.Created -= OnChanged;
// Do some cool stuff
}
答案 1 :(得分:2)
您不需要分配变量,sender
是FileSystemWatcher:
private static void OnChanged(object sender, FileSystemEventArgs e)
{
BuildingestionXml(string.Format(@"{0}\{1}",e.FullPath,e.Name));
Console.WriteLine(@"Second: Success sending{0}\{1}", e.FullPath, e.Name);
((FileSystemWatcher)sender).Dispose();
}