Search code examples
c#c#-4.0filesystemwatcheranonymous-methods

Can you create multiple watchers in a console app, using an anonymous delegate?


In another Question I asked, I got a tip on using an anonymous delegate. The functionality works for a single watcher but when I create three it only keeps the last one. Is this because of the anonymous delegate and is there a solution to this?

I have added the code.

foreach (ConfigurationSectionGroup sectionGroup in sectionGroups)
{
    if (sectionGroup.Name == "FileCheckerConfigGroup")
    {
        foreach(ConfigurationSection configurationSection in sectionGroup.Sections)
        {
            //FileChecker filecheck = new FileChecker();
            //filecheck.ProccessFolders(configurationSection);
            //FileChecker filecheck = new FileChecker();
            var section = ConfigurationManager.GetSection(configurationSection.SectionInformation.SectionName) as NameValueCollection;
            watcher = new FileSystemWatcher(section["inputDirectory"]);
            watcher.EnableRaisingEvents = true;
            watcher.Created += (sender, e) =>
            {
                using (var filecheck = new FileChecker())
                {
                    filecheck.ProccessFolders(configurationSection);
                }
            };                               
        }
    }
}

Solution

  • I think the problem is that you need within your lambda the element out of the foreach loop. Create a local copy of it within the loop and everything should work fine:

    foreach (ConfigurationSectionGroup sectionGroup in sectionGroups)
    {
        if (sectionGroup.Name == "FileCheckerConfigGroup")
        {
            foreach(ConfigurationSection configurationSection in sectionGroup.Sections)
            {
                //FileChecker filecheck = new FileChecker();
                //filecheck.ProccessFolders(configurationSection);
                //FileChecker filecheck = new FileChecker();
                var localConfigurationSectionCopy = configurationSection;
                var section = ConfigurationManager.GetSection(configurationSection.SectionInformation.SectionName) as NameValueCollection;
                watcher = new FileSystemWatcher(section["inputDirectory"]);
                watcher.EnableRaisingEvents = true;
                watcher.Created += (sender, e) =>
                {
                    using (var filecheck = new FileChecker())
                    {
                        filecheck.ProccessFolders(localConfigurationSectionCopy);
                    }
                };                               
            }
        }
    }
    

    For a better explanation whats going wrong take a look at this blog from Eric.