FileSystemWatcher Changed event is raised twice

前端 未结 30 3728
死守一世寂寞
死守一世寂寞 2020-11-22 06:01

I have an application where I am looking for a text file and if there are any changes made to the file I am using the OnChanged eventhandler to handle the event

30条回答
  •  一个人的身影
    2020-11-22 06:19

    Here's my approach :

    // Consider having a List named _changedFiles
    
    private void OnChanged(object source, FileSystemEventArgs e)
    {
        lock (_changedFiles)
        {
            if (_changedFiles.Contains(e.FullPath))
            {
                return;
            }
            _changedFiles.Add(e.FullPath);
        }
    
        // do your stuff
    
        System.Timers.Timer timer = new Timer(1000) { AutoReset = false };
        timer.Elapsed += (timerElapsedSender, timerElapsedArgs) =>
        {
            lock (_changedFiles)
            {
                _changedFiles.Remove(e.FullPath);
            }
        };
       timer.Start();
    }
    

    This is the solution I used to solve this issue on a project where I was sending the file as attachment in a mail. It will easily avoid the twice fired event even with a smaller timer interval but in my case 1000 was alright since I was happier with missing few changes than with flooding the mailbox with > 1 message per second. At least it works just fine in case several files are changed at the exact same time.

    Another solution I've thought of would be to replace the list with a dictionary mapping files to their respective MD5, so you wouldn't have to choose an arbitrary interval since you wouldn't have to delete the entry but update its value, and cancel your stuff if it hasn't changed. It has the downside of having a Dictionary growing in memory as files are monitored and eating more and more memory, but I've read somewhere that the amount of files monitored depends on the FSW's internal buffer, so maybe not that critical. Dunno how MD5 computing time would affect your code's performances either, careful =\

提交回复
热议问题