2
我一直在关注这里的指导FileSystemWatcher Changed event is raised twice。FileSystemwatcher获取文件列表
但是我有一个我正在看的文件列表,如果我一起删除了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
}
}
看起来像文件系统守望者在这个代码之前 - 当最后一次触发的值可以更新时,事件已经被调用4次,当我删除40个文件。我想这是PC速度有多快的一个功能。所以我会说上面的代码是有缺陷的。任何其他想法? – user1438082
为了公平起见,我认为你的答案非常好,我可以使用最好的答案。 – user1438082