2

使用 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(),它将有一个新路径。

我试图防止上述事件的太多侦听器实例导致内存泄漏。

4

2 回答 2

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
    }
于 2013-01-28T02:37:56.163 回答
3

您不需要分配变量,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();
}
于 2013-01-28T02:49:25.347 回答