【发布时间】:2014-03-06 21:27:17
【问题描述】:
我一直遵循这里的指导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
}
}
【问题讨论】:
标签: c# filesystemwatcher