C# 之 FileSystemWatcher事件多次触发的解决方法

摘要:
System.Threading.Timerm_timer=null;files=newList<//记录要处理的文件队列(2),初始化FileSystemWatcher和计时器fsw。Filter=“*.*”//Beginwatch.fsw.EnableRaisingEvents=true;超时.无限);backup=newList<

1、问题描述
   程序里需要监视某个目录下的文件变化情况: 一旦目录中出现新文件或者旧的文件被覆盖,程序需要读取文件内容并进行处理。于是使用了下面的代码:

public void Initial()
 {
   System.IO.FileSystemWatcher fsw = new System.IO.FileSystemWatcher();            
   fsw.Filter = "*.*";
   fsw.NotifyFilter = NotifyFilters.FileName  | 
                      NotifyFilters.LastWrite | 
                      NotifyFilters.CreationTime;

   // Add event handlers.
   fsw.Created += new FileSystemEventHandler(fsw_Changed);
   fsw.Changed += new FileSystemEventHandler(fsw_Changed);

   // Begin watching.
   fsw.EnableRaisingEvents = true;
 }

 void fsw_Changed(object sender, FileSystemEventArgs e)
 {
    MessageBox.Show("Changed", e.Name);
 }

  如果发现当一个文件产生变化时,Change事件被反复触发了好几次。这样可能的结果是造成同一文件的重复处理。

2、解决方案:
    通过一个计时器,在文件事件处理中让计时器延迟一段时间之后,再执行加载新的配置文件操作。这样可以避免对文件做一次操作触发了多个更改事件,而多次加载配置文件。

  研究了log4net的代码 - XmlConfigurator.cs,然后参照log4net对代码作了如下改动:
  基本思想是使用定时器,在事件触发时开始启动定时器,并记下文件名。当定时器到时,才真正对文件进行处理。
  (1)、定义变量

private int TimeoutMillis = 2000; //定时器触发间隔
System.IO.FileSystemWatcher fsw = new System.IO.FileSystemWatcher();
System.Threading.Timer m_timer = null;
List<String> files = new List<string>(); //记录待处理文件的队列

  (2)、初始化FileSystemWatcher和定时器

       fsw.Filter = "*.*";
       fsw.NotifyFilter = NotifyFilters.FileName  | 
                          NotifyFilters.LastWrite | 
                          NotifyFilters.CreationTime;

       // Add event handlers.
      fsw.Created += new FileSystemEventHandler(fsw_Changed);
      fsw.Changed += new FileSystemEventHandler(fsw_Changed);

      // Begin watching.
      fsw.EnableRaisingEvents = true;

      // Create the timer that will be used to deliver events. Set as disabled
      if (m_timer == null)
      {
         //设置定时器的回调函数。此时定时器未启动
         m_timer = new System.Threading.Timer(new TimerCallback(OnWatchedFileChange), 
                                      null, Timeout.Infinite, Timeout.Infinite);
      }

  (3)、文件监视事件触发代码:修改定时器,记录文件名待以后处理

        void fsw_Changed(object sender, FileSystemEventArgs e)
        {
            Mutex mutex = new Mutex(false, "FSW");
            mutex.WaitOne();
            if (!files.Contains(e.Name))
            {
                files.Add(e.Name);
            }
            mutex.ReleaseMutex();

            //重新设置定时器的触发间隔,并且仅仅触发一次
            m_timer.Change(TimeoutMillis, Timeout.Infinite);
        }

  (4)、定时器事件触发代码:进行文件的实际处理

        private void OnWatchedFileChange(object state)
        {
            List<String> backup = new List<string>();

            Mutex mutex = new Mutex(false, "FSW");
            mutex.WaitOne();
            backup.AddRange(files);
            files.Clear();
            mutex.ReleaseMutex();
       
            foreach (string file in backup)
            {
                MessageBox.Show("File Change", file + " changed");
            }     
        }

  将上面的代码整理一下,封装成一个类,使用上更加便利一些:

    public class WatcherTimer
    {
        private int TimeoutMillis = 2000;

        System.IO.FileSystemWatcher fsw = new System.IO.FileSystemWatcher();
        System.Threading.Timer m_timer = null;
        List<String> files = new List<string>();
        FileSystemEventHandler fswHandler = null;

        public WatcherTimer(FileSystemEventHandler watchHandler)
        {
            m_timer = new System.Threading.Timer(new TimerCallback(OnTimer), 
                         null, Timeout.Infinite, Timeout.Infinite);
            fswHandler = watchHandler;
        }

        public WatcherTimer(FileSystemEventHandler watchHandler, int timerInterval)
        {
            m_timer = new System.Threading.Timer(new TimerCallback(OnTimer), 
                        null, Timeout.Infinite, Timeout.Infinite);
            TimeoutMillis = timerInterval;
            fswHandler = watchHandler;
        }

        public void OnFileChanged(object sender, FileSystemEventArgs e)
        {
            Mutex mutex = new Mutex(false, "FSW");
            mutex.WaitOne();
            if (!files.Contains(e.Name))
            {
                files.Add(e.Name);
            }
            mutex.ReleaseMutex();
            m_timer.Change(TimeoutMillis, Timeout.Infinite);
        }

        private void OnTimer(object state)
        {
            List<String> backup = new List<string>();
            Mutex mutex = new Mutex(false, "FSW");
            mutex.WaitOne();
            backup.AddRange(files);
            files.Clear();
            mutex.ReleaseMutex();

            foreach (string file in backup)
            {
                fswHandler(this, new FileSystemEventArgs(
                       WatcherChangeTypes.Changed, string.Empty, file));
            }
        }
}

  在主调程序使用非常简单,只需要如下2步:
  1、生成用于文件监视的定时器对象

watcher = new WatcherTimer(fsw_Changed, TimeoutMillis);

  其中fsw_Changed是你自己的文件监视事件代码,将它传递给定时器对象的目的是用于定时到时的时候定时器对象可以调用你自己真正用于处理文件的代码。例如:

void fsw_Changed(object sender, FileSystemEventArgs e)
{
   //Read file.
   //Remove file from folder after reading
      
}

  2、将FileSystemWatcher的Create/Change/Rename/Delete等事件句柄关联到定时器的事件上

fsw.Created += new FileSystemEventHandler(watcher.OnFileChanged);
fsw.Changed += new FileSystemEventHandler(watcher.OnFileChanged);
fsw.Renamed += new RenamedEventHandler(watcher.OnFileChanged);
fsw.Deleted += new FileSystemEventHandler(watcher.OnFileChanged);

   这一步的目的是当有任何文件监视事件发生时,都能通知到定时器,定时器可以从最后一次发生的事件开始计时,在该计时未到时之前的任何事件都只会重新使计时器计时,而不会真正触发文件监视事件。

  要注意的是,采用了以上的代码后,你真正用于处理文件监视事件的代码被调用的时候只有其中的e.Name是有值的。考虑到被监视的文件目录应该已经知道了,所以e.FullPath被赋值为string.Empty并不是不能接受的。

免责声明:文章转载自《C# 之 FileSystemWatcher事件多次触发的解决方法》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇【mysql】【转发】Cannot proceed because system tables used by Event Scheduler were found damaged at server startSQLServer触发器下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

版本基线自动化之windows

1、背景: 目前项目维护周期过程中,制作调试版本和对外发布版本次数比较频繁,流程过于繁琐和随意,且打包制作人成为瓶颈,为了规范版本基线流程和实现全员自动化参与,拟定版本基线自动化方案。  2、目标: 版本基线自动化方案的实施,主要任务分为配置管理自动化,编译做包自动化,版本发布自动化。主要目标是实现一键式做包和发布,减少人为误操作、释放人力资源、提高开发效...

Filebeat原理与简单配置入门

Filebeat工作原理 Filebeat由两个主要组件组成:prospectors 和 harvesters。这两个组件协同工作将文件变动发送到指定的输出中。 Harvester(收割机):负责读取单个文件内容。每个文件会启动一个Harvester,每个Harvester会逐行读取各个文件,并将文件内容发送到制定输出中。Harvester负责打开和关闭...

c语言入门-01

当我们学c语言我们学些什么. [1]编译机制 当我们写好c的代码,生产了程序,这中间到底做了些什么?    这个就是c语言的编译过程 我们分别来解析这上面的过程。 我们写出我们第一个c程序。   1 #include<stdio.h> 2 3 int main(){ 4 // print hello world...

在原生 html 中使用 vue,在浏览器中直接运行 .vue 文件,在 vue 中使用 leaflet

vue3-in-html 在html中使用vue3,不依赖nodejs和webpack,不依赖脚手架 demo源码 https://gitee.com/s0611163/vue3-in-html 功能 编写了几个简单的组件,使用了element-plus和vuex 在vue3组件中使用leaflet实现电子地图 特色 原生 html 开发,不依赖 n...

MySQL备份,使用xtrabackup备份全实例数据时,会造成锁等待吗?那么如果使用mysqldump进行备份呢?

一、xtrabackup和mysqldump会造成锁等待吗? xtrabackup会,它在备份时会产生短暂的全局读锁FTWL(flush table with read lock),用于拷贝frm/MYD/MYI等文件,以及记录binlog信息。如果MyISAM表的数据量非常大,则拷贝时间就越长,加锁的时间也越长 mysqldump有可能会。如果只是添加...

Perl命令行常见用法及技巧

Perl命令行常见用法及技巧 作者:懒人运维 来源: 懒人运维        替换 将所有C程序中的foo替换成bar,旧文件备份成.bak perl -p -i.bak -e ’s/foo/bar/g’ *.c 很强大的功能,特别是在大程序中做重构。记得只有在UltraEdit用过。 如果你不想备份,就直接写成 perl -p -i -e 或者更简单...