gpt4 book ai didi

c# - 如何实现以 ConcurrentDictionary 为条件的 TryRemove?

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:21 26 4
gpt4 key购买 nike

<分区>

最近I had a need对于我可以从多个线程更新的 Dictionary,这项工作的明显候选者是内置 ConcurrentDictionary .不幸的是,我最终没有使用它,而是使用了一个普通的 Dictionary 保护 lock,因为一个致命的限制:TryRemove不提供允许有条件地删除元素的重载。可用的 TryRemove 方法删除并返回删除的元素,但在我的例子中,只有在同一工作流之前插入元素时才必须删除该元素。从不同的工作流中删除一个元素(即使是几分之一微秒)可能会产生不良后果,我宁愿不必解决。所以我的问题是:是否可以使用线程安全的条件 TryRemove 扩展方法修改现有的 ConcurrentDictionary 类?

这里是我的用例供引用。使用 AddOrUpdate 安全地填充字典。方法:

var dict = new ConcurrentDictionary<string, CancellationTokenSource>();
var cts = dict.AddOrUpdate("Key1", key => new CancellationTokenSource(),
(key, existingValue) =>
{
existingValue.Cancel();
return new CancellationTokenSource();
});

稍后我想通过调用下面不存在的方法来删除我之前插入的值:

var removed = dict.TryRemove("Key1", (key, existingValue) =>
{
return existingValue == cts;
});

这是所需方法的签名:

public static bool TryRemove<TKey, TValue>(
this ConcurrentDictionary<TKey, TValue> source, TKey key,
Func<TKey, TValue, bool> predicate)
{
// Is it possible?
}

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com