这里是一个I produckerConsumer Collection<T>
< a href="Concoltrocol Dictionary<TKey, TValue&code>该收藏的收藏收藏库是类型 KuePa<TKey.comst&com; < a scode.
public class ConcurrentDictionaryProducerConsumer<TKey, TValue>
: IProducerConsumerCollection<KeyValuePair<TKey, TValue>>
{
private readonly ConcurrentDictionary<TKey, TValue> _dictionary;
private readonly ThreadLocal<IEnumerator<KeyValuePair<TKey, TValue>>> _enumerator;
public ConcurrentDictionaryProducerConsumer(
IEqualityComparer<TKey> comparer = default)
{
_dictionary = new(comparer);
_enumerator = new(() => _dictionary.GetEnumerator());
}
public bool TryAdd(KeyValuePair<TKey, TValue> entry)
{
if (!_dictionary.TryAdd(entry.Key, entry.Value))
throw new DuplicateKeyException();
return true;
}
public bool TryTake(out KeyValuePair<TKey, TValue> entry)
{
// Get a cached enumerator that is used only by the current thread.
IEnumerator<KeyValuePair<TKey, TValue>> enumerator = _enumerator.Value;
while (true)
{
enumerator.Reset();
if (!enumerator.MoveNext())
throw new InvalidOperationException();
entry = enumerator.Current;
if (!_dictionary.TryRemove(entry)) continue;
return true;
}
}
public int Count => _dictionary.Count;
public bool IsSynchronized => false;
public object SyncRoot => throw new NotSupportedException();
public KeyValuePair<TKey, TValue>[] ToArray() => _dictionary.ToArray();
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
=> _dictionary.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
=> throw new NotSupportedException();
public void CopyTo(Array array, int index) => throw new NotSupportedException();
}
public class DuplicateKeyException : InvalidOperationException { }
用法示例:
BlockingCollection<KeyValuePair<string, Item>> collection
= new(new ConcurrentDictionaryProducerConsumer<string, Item>());
//...
try { collection.Add(KeyValuePair.Create(key, item)); }
catch (DuplicateKeyException) { Console.WriteLine($"The {key} was rejected."); }
counting.TryTake
方法删除了 < a href=> > Conctituue NoDuplices<T> , 我张贴了 < a href=" https://stackoverffflow.com/Mis/765669/conminal-and-uniquelements/7536>
avidition: calling counting.TryAdd(项目);
没有预期的返回行为,如果钥匙存在的话, /code>。任何试图在 DupreyKeyExpeption
中无一例外地添加重复的关键结果。请查看上述