仅当队列中不存在项目时,才将其添加到队列中

  • 本文关键字:队列 添加 不存在 项目 c#
  • 更新时间 :
  • 英文 :


我正在使用队列处理zip文件。因此,每当新的 zip 文件到达指定路径时,file_info 都将使用
fileQueue.Enqueue(IFile);现在,我应该仅在文件不存在时才将文件添加到队列中。我试图实现IEqualityComparer<T>接口和

public bool Equals(T x, T y)
{
   object xValue = _propertyInfo.GetValue(x, null);
   object yValue = _propertyInfo.GetValue(y, null);
   return xValue.Equals(yValue);
} 

public int GetHashCode(T obj)
{
   object propertyValue = _propertyInfo.GetValue(obj, null);
   if (propertyValue == null)
      return 0;
   else
      return propertyValue.GetHashCode();
} 

我有一个接口来获取文件信息

public interface IFile
{        
   string FilePath { get; set; }
}

另一个队列对象

public Queue<IFile> fileQueue = new Queue<IFile>();

任何人都可以建议如何在再次将其添加到队列之前检查该文件是否已存在于队列中。提前非常感谢你。

如果你想要一个快速执行的解决方案(并且希望避免每次添加 smth 时遍历整个队列),你需要实现你自己的队列。

像这样

public class MyQueue
{
    private Queue<IFile> _queue;
    private HashSet<int> hashes;
    public void Add(IFile file)
    {
        var hash = GetHash(file);
        if (hashes.Add(hash))
        {
            _queue.Enqueue(file);
        }
    }
}

基本上有一个"目录" - 作为哈希集实现(用于保存唯一值列表)

注意:一旦您开始使用队列和消息 - 这种架构背后的整个想法 - 是消息应该是幂等的。这意味着 - 没关系 您将相同的消息多次添加到队列中。

if(!fileQueue.Any(x => x.FilePath == file.FilePath))
   fileQueue.Enqueue(file)

最新更新