我一直在遵循这里的指导,FileSystemWatcher Changed event is raised twice。
然而,我有一个文件列表,我正在看,所以如果我删除20个文件在一起,事件被称为20次。这是意料之中的,而且运作良好。
如何只为20个“同时”文件更改触发一次事件(即,在下面Onchanged的第一个实例中的代码完成之前,我如何能够忽略所有其他文件更改。现在Onchanged被叫了20次。)?
private void Main_Load(object sender, EventArgs e)
{
public static List<FileSystemWatcher> watchers = new List<FileSystemWatcher>();
UpdateWatcher();
}
public void OnChanged(object sender, FileSystemEventArgs e)
{
try
{
Logging.Write_To_Log_File("Item change detected " + e.ChangeType + " " + e.FullPath + " " + e.Name, MethodBase.GetCurrentMethod().Name, "", "", "", "", "", "", 2);
watchers.Clear();
foreach (FileSystemWatcher element in MyGlobals.watchers)
{
element.EnableRaisingEvents = false;
}
//Do some processing on my list of files here....
return;
}
catch (Exception ex)
{
// If exception happens, it will be returned here
}
finally
{
foreach (FileSystemWatcher element in MyGlobals.watchers)
{
element.EnableRaisingEvents = true;
}
}
}
public void UpdateWatcher() // Check Items
{
try
{
watchers.Clear();
for (int i = 0; i < MyGlobals.ListOfItemsToControl.Count; i++) // Loop through List with for
{
FileSystemWatcher w = new FileSystemWatcher();
w.Path = Path.GetDirectoryName(MyGlobals.ListOfItemsToControl[i].sItemName); // File path
w.Filter = Path.GetFileName(MyGlobals.ListOfItemsToControl[i].sItemName); // File name
w.Changed += new FileSystemEventHandler(OnChanged);
w.Deleted += new FileSystemEventHandler(OnChanged);
w.Created += new FileSystemEventHandler(OnChanged);
w.EnableRaisingEvents = true;
watchers.Add(w);
}
}
catch (Exception ex)
{
// If exception happens, it will be returned here
}
}发布于 2014-03-06 21:43:43
这里的关键点是“在一起”对你意味着什么。毕竟,系统对每个系统都执行独立的删除操作,这在技术上意味着它们不是在完全相同的时间被删除的,但是如果您只想接近它们,那么假设它们都在5秒内被删除,那么我们只希望OnChange触发一次,您可以执行以下操作。请注意,这不处理重命名更改通知。你没在听,所以我以为你不需要听。
根据您的使用情况,您可能需要将5秒窗口更改为一个小窗口。
class SlowFileSystemWatcher : FileSystemWatcher
{
public delegate void SlowFileSystemWatcherEventHandler(object sender, FileSystemEventArgs args);
public event SlowFileSystemWatcherEventHandler SlowChanged;
public DateTime LastFired { get; private set; }
public SlowFileSystemWatcher(string path)
: base(path)
{
Changed += HandleChange;
Created += HandleChange;
Deleted += HandleChange;
LastFired = DateTime.MinValue;
}
private void SlowGeneralChange(object sender, FileSystemEventArgs args)
{
if (LastFired.Add(TimeSpan.FromSeconds(5)) < DateTime.UtcNow)
{
SlowChanged.Invoke(sender, args);
LastFired = DateTime.UtcNow;
}
}
private void HandleChange(object sender, FileSystemEventArgs args)
{
SlowGeneralChange(sender, args);
}
protected override void Dispose(bool disposing)
{
SlowChanged = null;
base.Dispose(disposing);
}
}https://stackoverflow.com/questions/22236363
复制相似问题