FileSystemWatcher Changed event is raised twice

前端 未结 30 3797
死守一世寂寞
死守一世寂寞 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:37

    I wanted to react only on the last event, just in case, also on a linux file change it seemed that the file was empty on the first call and then filled again on the next and did not mind loosing some time just in case the OS decided to do some file/attribute change.

    I am using .NET async here to help me do the threading.

        private static int _fileSystemWatcherCounts;
        private async void OnChanged(object sender, FileSystemEventArgs e)
        {
            // Filter several calls in short period of time
            Interlocked.Increment(ref _fileSystemWatcherCounts);
            await Task.Delay(100);
            if (Interlocked.Decrement(ref _fileSystemWatcherCounts) == 0)
                DoYourWork();
        }
    

提交回复
热议问题