【发布时间】:2011-06-24 06:55:40
【问题描述】:
我想以一种有效的方式从队列中删除重复的条目。 队列有一个自定义类,包含 DateTime 和 FullPath 以及其他一些东西
private Queue<MyCustomClass> SharedQueue;
类中的 DateTime 是插入队列时的时间戳。我想使用的逻辑如下:如果 FullPath 在 4 秒窗口内相同(即如果在重复完整路径的 4 秒内添加到队列中),则从队列中删除重复项。我有想要观看的活动,但仍会出现一些重复的活动,这没关系。
我正在使用 c# 2.0 和 FileSystemWatcher 类和一个工作队列。
有很多方法可以做到这一点: 每次添加项目时修剪队列,或者当我处理队列时跳过当前重复项目的处理。
或者我应该使用“全局私有”变量 Dictionary 吗?这样我可以快速搜索吗?还是队列的本地副本?如果有很多文件事件,最好将本地队列限制为 100 个项目?虽然在我的情况下,它“应该”只是在一个文件夹中监控相对较少的文件......但事情总是在变化......
感谢您的帮助。
:编辑:美国东部时间 2 月 10 日 8:54: 因此,据我所知,我决定实施一个很好的简单解决方案。 我不认为我持有 Dict 键太久...
:编辑:美国东部标准时间 2 月 10 日 9:53:已更新,因为我的字典不能包含重复值。
public void QueueInput(HotSynchUnit.RcdFSWFile rcd)
// start the worker thread when program starts.
// call Terminate.Set() in the programs exit routine or close handler etc.
{
// lock shared queue
lock (SharedQueue)
{
if (!IsDuplicateQueueInput(rcd)) // only add unique values to queue
{
SharedQueue.Enqueue(rcd);
SomethingToDo.Set();
}
}
} // public void QueueInput
private bool IsDuplicateQueueInput(HotSynchUnit.RcdFSWFile rcd)
/* Return true if the object is a duplicate object.
* Pseudo Code:
*
* isDuplicate = false
* Lock Dictionary
* -If lastTimeStamp > 4 seconds ago then // Optimization: save lastTimeStamp
* if Dict.Count > 0 then clear Dictionary
* return isDuplicate
* -If not Dict.TryGetValue(sPath, dtTimeStamp) then
* Dict.AddKey()
* -Else
* Compare key timestamp to Currenttime
* if key timestamp is <= 4 seconds ago then
* IsDuplicate = True
*
* Dict.RemoveKey()
* Dict.AddKey()
*
* return isDuplicate
*/
{
// put real code here
}
【问题讨论】:
-
为什么是“全球私有”字典?为什么不把它和你的队列放在同一个范围内呢?
-
实际上就是这样。我的错。
-
感谢@StevenJeuris 在我入队之前检查的想法 - 我忘记了我在那里有那个例程。我不想覆盖或扩展类...
标签: c# queue filesystemwatcher no-duplicates