惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
有赞技术团队
有赞技术团队
J
Java Code Geeks
H
Hackread – Cybersecurity News, Data Breaches, AI and More
美团技术团队
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Hugging Face - Blog
Hugging Face - Blog
人人都是产品经理
人人都是产品经理
酷 壳 – CoolShell
酷 壳 – CoolShell
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
C
Check Point Blog
博客园 - 【当耐特】
The GitHub Blog
The GitHub Blog
Recent Announcements
Recent Announcements
The Cloudflare Blog
Microsoft Azure Blog
Microsoft Azure Blog
腾讯CDC
Vercel News
Vercel News
IT之家
IT之家
MyScale Blog
MyScale Blog
博客园_首页
Martin Fowler
Martin Fowler
WordPress大学
WordPress大学
罗磊的独立博客

博客园 - sema

Netron开发快速上手(二):Netron序列化 发布一个免费开源软件-- PAD流程图绘制软件PADFlowChart Netron源码解读(一):GraphControl画布对象 Netron开发快速上手(一):GraphControl,Shape,Connector和Connection IBatis.Net 中的数据类型转换 深入浅出之正则表达式(二) 深入浅出之正则表达式(一) 在.NET环境中实现每日构建(Daily Build)--NAnt篇 自动向网页Post信息并提取返回的信息 在C#中利用自动化模型操纵Word VS.NET 2003集成环境插件开发指南(三)----操纵VS开发环境(完结篇) VS.NET 2003集成环境插件开发指南(二)----使用窗口 VS.NET 2003集成环境插件开发指南(一)----操纵菜单 后期写作计划 利用反射解决QueryString和Session中的参数绑定问题 开发Visual Studio风格的用户界面--MagicLibrary使用指南 Log4Net使用指南 一些写英文简历的词汇吧 关于一些大学课程名的中文翻译
FileSystemWatcher事件多次触发的解决方法
sema · 2008-07-04 · via 博客园 - sema

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、解决方案:
在Google上进行一番搜索后,得到了下面的一段信息: <<http://www.cnblogs.com/RicCC/archive/2006/12/16/filesystem-watcher.html>>
"...可以参考log4net的做法。通过一个计时器,在文件事件处理中让计时器延迟一段时间之后,再执行加载新的配置文件操作。这样可以避免对文件做一次操作触发了多个更改事件,而多次加载配置文件。"

研究了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(
thisnew 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并不是不能接受的。

完整的代码请下载示例程序。