How to dispose of event listeners from FileSystemWatcher events

这一生的挚爱 提交于 2019-12-13 02:35:20

问题


Using FileSystemWatcher, is there a way to dispose of instances of event listeners after an event has fired?

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.

My program looks like this:

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);
}

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.


回答1:


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();
}



回答2:


In you EventHandler you can just un-assign the event, But you will have to declare the FileSystemWatcher as a variable.

Example

    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
    }


来源:https://stackoverflow.com/questions/14554668/how-to-dispose-of-event-listeners-from-filesystemwatcher-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!