FileSystemWatcher触发多次Change事件的解决办法 .
最近要用到FileSystemWatcher来监控某个目录中的文件是否发生改变,如果改变就执行相应的操作。但在开发过程中,发现FileSystemWatcher在文件创建或修改后,会触发多个Created或Changed事件,具体原因就是处理文件的过程中执行了多次文件系统操作,触发了多次事件。具体可以参看微软的关于FileSystemWatcher这方面的解释:Troubleshooting FileSystemWatcher Components,另外我在网上发现 Consolidate Multiple FileSystemWatcher Events 关于这方面的解决办法,比较实用,方便快速引入到项目中。
来自MSDN的问题说明
Troubleshooting FileSystemWatcher Components
You may encounter the following situations while working with the FileSystemWatcher component:
UNC Path Names Not Accepted on Windows NT 4.0 Computers
If you are working with a FileSystemWatcher component on a Windows NT version 4.0 computer and trying to set its path to monitor file system activity on a different Windows NT version 4.0 computer, you will not be able to specify a UNC-based path value in the Path property to point to the computer in question. You can only set UNC-based values when working on Windows 2000 computers.
Cannot Watch Windows 95 or Windows 98 Directories
If you set your FileSystemWatcher component to reference a directory on a Windows 95 or Windows 98 computer, you will receive an error about an invalid directory path when the project runs. When using FileSystemWatcher, you cannot watch directories on computers running Windows 95 or Windows 98.
Multiple Created Events Generated for a Single Action
You may notice in certain situations that a single creation event generates multiple Created events that are handled by your component. For example, if you use aFileSystemWatcher component to monitor the creation of new files in a directory, and then test it by using Notepad to create a file, you may see two Created events generated even though only a single file was created. This is because Notepad performs multiple file system actions during the writing process. Notepad writes to the disk in batches that create the content of the file and then the file attributes. Other applications may perform in the same manner. Because FileSystemWatcher monitors the operating system activities, all events that these applications fire will be picked up.
Note Notepad may also cause other interesting event generations. For example, if you use the ChangeEventFilter to specify that you want to watch only for attribute changes, and then you write to a file in the directory you are watching using Notepad, you will raise an event . This is because Notepad updates theArchived attribute for the file during this operation.
Unexpected Events Generated on Directories
Changing a file within a directory you are monitoring with a FileSystemWatcher component generates not only a Changed event on the file but also a similar event for the directory itself. This is because the directory maintains several types of information for each file it contains — the names and sizes of files, their modification dates, attributes, and so on. Whenever one of these attributes changes, a change is associated with the directory as well.
解决方案
The .NET framework provides a FileSystemWatcher class that can be used to monitor the file system for changes. My requirements were to monitor a directory for new files or changes to existing files. When a change occurs, the application needs to read the file and immediately perform some operation based on the contents of the file.
While doing some manual testing of my initial implementation it was very obvious that theFileSystemWatcher was firing multiple events whenever I made a change to a file or copied a file into the directory being monitored. I came across the following in the MSDNdocumentation’s Troubleshooting FileSystemWatcher Components
Multiple Created Events Generated for a Single Action
You may notice in certain situations that a single creation event generates multiple Created events that are handled by your component. For example, if you use a FileSystemWatcher component to monitor the creation of new files in a directory, and then test it by using Notepad to create a file, you may see two Created events generated even though only a single file was created. This is because Notepad performs multiple file system actions during the writing process. Notepad writes to the disk in batches that create the content of the file and then the file attributes. Other applications may perform in the same manner. Because FileSystemWatcher monitors the operating system activities, all events that these applications fire will be picked up.
Note: Notepad may also cause other interesting event generations. For example, if you use the ChangeEventFilter to specify that you want to watch only for attribute changes, and then you write to a file in the directory you are watching using Notepad, you will raise an event. This is because Notepad updates the Archived attribute for the file during this operation.
I did some searching and was surprised that .NET did not provide any kind of wrapper around the FileSystemWatcher to make it a bit more user friendly. I ended up writing my own wrapper that would monitor a directory and only throw one event when a new file was created, or an existing file was changed.
In order to consolidate the multiple FileSystemWatcher events down to a single event, I save the timestamp when each event is received, and I check back every so often (using a Timer) to find paths that have not caused additional events in a while. When one of these paths is ready, a single Changed event is fired. An additional benefit of this technique is that the event from the FileSystemWatcher is handled very quickly, which could help prevent its internal buffer from filling up.
Here is the code for a DirectoryMonitor class that consolidates multiple Win32 events into a single Change event for each change:
解决方案代码
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.Threading;
- namespace ShareReadFile
- {
- public delegate void FileSystemEvent(String path);
- public interface IDirectoryMonitor
- {
- event FileSystemEvent Change;
- void Start();
- }
- public class DirectoryMonitor : IDirectoryMonitor
- {
- private readonly FileSystemWatcher m_fileSystemWatcher = new FileSystemWatcher();
- private readonly Dictionary<string, DateTime> m_pendingEvents = new Dictionary<string, DateTime>();
- private readonly Timer m_timer;
- private bool m_timerStarted = false;
- public DirectoryMonitor(string dirPath)
- {
- m_fileSystemWatcher.Path = dirPath;
- m_fileSystemWatcher.IncludeSubdirectories = false;
- m_fileSystemWatcher.Created += new FileSystemEventHandler(OnChange);
- m_fileSystemWatcher.Changed += new FileSystemEventHandler(OnChange);
- m_timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
- }
- public event FileSystemEvent Change;
- public void Start()
- {
- m_fileSystemWatcher.EnableRaisingEvents = true;
- }
- private void OnChange(object sender, FileSystemEventArgs e)
- {
- // Don't want other threads messing with the pending events right now
- lock (m_pendingEvents)
- {
- // Save a timestamp for the most recent event for this path
- m_pendingEvents[e.FullPath] = DateTime.Now;
- // Start a timer if not already started
- if (!m_timerStarted)
- {
- m_timer.Change(100, 100);
- m_timerStarted = true;
- }
- }
- }
- private void OnTimeout(object state)
- {
- List<string> paths;
- // Don't want other threads messing with the pending events right now
- lock (m_pendingEvents)
- {
- // Get a list of all paths that should have events thrown
- paths = FindReadyPaths(m_pendingEvents);
- // Remove paths that are going to be used now
- paths.ForEach(delegate(string path)
- {
- m_pendingEvents.Remove(path);
- });
- // Stop the timer if there are no more events pending
- if (m_pendingEvents.Count == 0)
- {
- m_timer.Change(Timeout.Infinite, Timeout.Infinite);
- m_timerStarted = false;
- }
- }
- // Fire an event for each path that has changed
- paths.ForEach(delegate(string path)
- {
- FireEvent(path);
- });
- }
- private List<string> FindReadyPaths(Dictionary<string, DateTime> events)
- {
- List<string> results = new List<string>();
- DateTime now = DateTime.Now;
- foreach (KeyValuePair<string, DateTime> entry in events)
- {
- // If the path has not received a new event in the last 75ms
- // an event for the path should be fired
- double diff = now.Subtract(entry.Value).TotalMilliseconds;
- if (diff >= 75)
- {
- results.Add(entry.Key);
- }
- }
- return results;
- }
- private void FireEvent(string path)
- {
- FileSystemEvent evt = Change;
- if (evt != null)
- {
- evt(path);
- }
- }
- }
- }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading; namespace ShareReadFile
{
public delegate void FileSystemEvent(String path); public interface IDirectoryMonitor
{
event FileSystemEvent Change;
void Start();
} public class DirectoryMonitor : IDirectoryMonitor
{
private readonly FileSystemWatcher m_fileSystemWatcher = new FileSystemWatcher();
private readonly Dictionary<string, DateTime> m_pendingEvents = new Dictionary<string, DateTime>();
private readonly Timer m_timer;
private bool m_timerStarted = false; public DirectoryMonitor(string dirPath)
{
m_fileSystemWatcher.Path = dirPath;
m_fileSystemWatcher.IncludeSubdirectories = false;
m_fileSystemWatcher.Created += new FileSystemEventHandler(OnChange);
m_fileSystemWatcher.Changed += new FileSystemEventHandler(OnChange); m_timer = new Timer(OnTimeout, null, Timeout.Infinite, Timeout.Infinite);
} public event FileSystemEvent Change; public void Start()
{
m_fileSystemWatcher.EnableRaisingEvents = true;
} private void OnChange(object sender, FileSystemEventArgs e)
{
// Don't want other threads messing with the pending events right now
lock (m_pendingEvents)
{
// Save a timestamp for the most recent event for this path
m_pendingEvents[e.FullPath] = DateTime.Now; // Start a timer if not already started
if (!m_timerStarted)
{
m_timer.Change(100, 100);
m_timerStarted = true;
}
}
} private void OnTimeout(object state)
{
List<string> paths; // Don't want other threads messing with the pending events right now
lock (m_pendingEvents)
{
// Get a list of all paths that should have events thrown
paths = FindReadyPaths(m_pendingEvents); // Remove paths that are going to be used now
paths.ForEach(delegate(string path)
{
m_pendingEvents.Remove(path);
}); // Stop the timer if there are no more events pending
if (m_pendingEvents.Count == 0)
{
m_timer.Change(Timeout.Infinite, Timeout.Infinite);
m_timerStarted = false;
}
} // Fire an event for each path that has changed
paths.ForEach(delegate(string path)
{
FireEvent(path);
});
} private List<string> FindReadyPaths(Dictionary<string, DateTime> events)
{
List<string> results = new List<string>();
DateTime now = DateTime.Now; foreach (KeyValuePair<string, DateTime> entry in events)
{
// If the path has not received a new event in the last 75ms
// an event for the path should be fired
double diff = now.Subtract(entry.Value).TotalMilliseconds;
if (diff >= 75)
{
results.Add(entry.Key);
}
} return results;
} private void FireEvent(string path)
{
FileSystemEvent evt = Change;
if (evt != null)
{
evt(path);
}
}
}
}
FileSystemWatcher触发多次Change事件的解决办法 .的更多相关文章
- bootstrapValidator关于js,jquery动态赋值不触发验证(不能捕获“程序赋值事件”)解决办法
//触发oninput事件 //propertychange 兼容ie678 $('#captainName').on('input propertychange', function() { }); ...
- 改变input的值不会触发change事件的解决思路
通常来说,如果我们自己通过 value 改变了 input 元素的值,我们肯定是知道的,但是在某些场景下,页面上有别的逻辑在改变 input 的 value 值,我们可能希望能在这个值发生变化的时候收 ...
- input输入框file类型第二次不触发onchange事件的解决办法,简单有效
在网上看了很多办法,现在将网上大部分说法总结如下: 网上说法: 原因:选择一次后onchange事件没有绑定到input标签上: 解决办法:拷贝一份input标签的副本,每次选择后对原input ...
- js设置下拉框选中后change事件无效解决
下拉框部分代码: <select id="bigType"> <option value="">请选择</option> & ...
- jQuery 设置select,radio的值,无法自动触发绑定的change事件
一.问题 今天在对select和radio做change事件绑定后,手动设置其value值,但是不能触发change事件 二.解决 使用trigger方法手动触发
- jquery 怎么触发select的change事件
可以使用jQuery的trigger() 方法来响应事件 定义和用法 trigger() 方法触发被选元素的指定事件类型. 语法 $(selector).trigger(event,[param1,p ...
- 关于webuploader 在ie9上不能触发 input 的 change 事件
上传文件用了 webuploader,ie9以上及其它浏览器正常执行js ,但是在ie9上点击input 无效,不能触发change 事件. 第一反应是ie9 需要使用flash 上传文件 原因: . ...
- 如何触发react input change事件
页面用react来进行开发的,想触发react组件里面input的change事件,用Jquery的trigger来触发没有效果,必须使用原生的事件来进行触发. var event = new Eve ...
- WDatePicker 屏蔽onchange事件的解决办法
受下面文章的启发,使用DatePicker自带的年月日相关的change事件,可以“勉强”实现input控件的onchange(),直接上代码: 1.第一种方式:利用DatePicker提供的年.月. ...
随机推荐
- 一个在 Java VM 上使用可观测的序列来组成异步的、基于事件的程序的库 RxJava,相当好
https://github.com/ReactiveX/RxJava https://github.com/ReactiveX/RxAndroid RX (Reactive Extensions,响 ...
- LINQ标准查询操作符(四) —AsEnumerable,Cast,OfType,ToArray,ToDictionary,ToList,ToLookup,First,Last,ElementAt
十.转换操作符 转换操作符是用来实现将输入对象的类型转变为序列的功能.名称以“As”开头的转换方法可更改源集合的静态类型但不枚举(延迟加载)此源集合.名称以“To”开头的方法可枚举(即时加载)源集合并 ...
- Django 的 CSRF 保护机制(转)
add by zhj:假设用户登录了网站A,而在网站B中有一个CSRF攻击标签,点击这个标签就会访问网站A,如果前端数据(包括sessionid)都放在本地存储的话, 当在网站B点击CSRF攻击标签时 ...
- oracle学习 四(持续更新中)无法为表空间 MAXDATA 中的段创建 INITIAL 区
解决建立表的时候出现的 ORA-01658: 无法为表空间 MAXDATA 中的段创建 INITIAL 区 出现这个问题是因为表空间的大小不足,可以给他扩容这样的话也会多出来一个数据文件.具体写法如下 ...
- Guid函数
使用GUID函数可以得到一个不重复的序列号,但是考虑到会出现并发等一系列情况,所以建议使用时间+GUID的方法去生成一串序列号 ,一般语法如下: string str = System.Guid.Ne ...
- How Tomcat Works(十四)
我们已经知道,在tomcat中有四种类型的servlet容器,分别为Engine.Host.Context 和Wrapper,本文接下来对tomcat中Wrapper接口的标准实现进行说明. 对于每个 ...
- [MySQL] 字符集和排序方式
字符串类型 MySQL的字符串分为两大类: 1)二进制字符串:即一串字节序列,对字节的解释不涉及字符集,因此它没有字符集和排序方式的概念 2)非二进制字符串:由字符构成的序列,字符集用来解释字符串的内 ...
- Javascript 正则表达式校验数字
$("input[datatype=number]").blur(function () { var str = $(this).val( ...
- 无责任Windows Azure SDK .NET开发入门篇三[使用Azure AD 管理用户信息--3.2 Create创建用户]
3.2 Create创建用户 [HttpPost, Authorize] public async Task<ActionResult> Create( [Bind(Include = & ...
- sc7731 Android 5.1 Camera 学习之二 framework 到 HAL接口整理
前面已经分析过,Client端发起远程调用,而实际完成处理任务的,是Server端的 CameraClient 实例.远程client 和 server是两个不同的进程,它们使用binder作为通信工 ...