问题描述
使用FileSystemWatcher,有没有办法在事件触发后处置事件侦听器的实例?
Using FileSystemWatcher, is there a way to dispose of instances of event listeners after an event has fired?
我的程序基本上在新创建的文件夹中侦听batch.complete.xml文件的创建.程序检测到文件已创建后,就无需继续在此文件夹中进行侦听了.
My program basically listens for the creation of a batch.complete.xml file in newly created folders. Once the program detects that the file has been created there is no need to continue listening in this folder.
我的程序如下:
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);
}
因此,当触发以上事件时,除非显式调用watchxmlfile()并将其具有新路径,否则我不再需要在"batchfolderpath"中监视事件.
So when the above event is fired I no longer need to watch for events in "batchfolderpath" unless watchxmlfile() is explicitly called which will have a new path.
我正在尝试防止上述事件的过多侦听器实例引起的内存泄漏.
I am trying to prevent memory leaks from too many instances of listeners for the above event.
推荐答案
您不需要分配变量,sender
是FileSystemWatcher:
You don't need to assign a variable, sender
is the 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();
}
这篇关于如何处理FileSystemWatcher事件中的事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!