C#   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c# – ConcurrentStack:如何检查是否包含对象?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
如何检查它是否包含堆栈中的特定对象?

private ConcurrentStack<int> cs = new ConcurrentStack<int>();
cs.Push(1);

解决方法

方法 Stack<T>.ContainsConcurrentStack<T>-class中不可用.我想因为那不是线程安全的.

因此,如果您需要它,您必须使用锁,然后您可以使用Enumerable.Contains:

private ConcurrentStack<int> cs = new ConcurrentStack<int>();
private Object csLockObject  = new Object();

bool contains = false;
lock (csLockObject)
{
    contains = cs.Contains(1);
}

但是,当您枚举此快照时,另一个线程可能会向堆栈添加项目或从堆栈中删除项目.如果您想要防止在添加/删除的位置还需要锁定.

好吧,你可以使用这样的类,它使用COncurrentDictionary来检查它是否是唯一的:

public class ConcurrentUniqueStack<T>
{
    private readonly ConcurrentDictionary<T,int> _itemUnique; // there is no ConcurrentHashSet so we need to use a Key-only Dictionary
    private readonly ConcurrentStack<T> _stack;

    public ConcurrentUniqueStack() : this(EqualityComparer<T>.Default)
    {
    }
    public ConcurrentUniqueStack(IEqualityComparer<T> comparer)
    {
        _stack = new ConcurrentStack<T>();
        _itemUnique = new ConcurrentDictionary<T,int>(comparer);
    }

    public bool TryPush(T item)
    {
        bool unique = _itemUnique.TryAdd(item,1);
        if (uniquE)
        {
            _stack.Push(item);
        }

        return unique;
    }
    public bool TryPop(out T result)
    {
        bool CouldBeRemoved = _stack.TryPop(out result);
        if (CouldBeRemoved)
        {
            _itemUnique.TryRemove(result,out int whatever);
        }
        return CouldBeRemoved;
    }

    public bool TryPeek(out T result) => _stack.TryPeek(out result);
}

大佬总结

以上是大佬教程为你收集整理的c# – ConcurrentStack:如何检查是否包含对象?全部内容,希望文章能够帮你解决c# – ConcurrentStack:如何检查是否包含对象?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。