- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
<分区>
最近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?
}
这个问题在这里已经有了答案: When will ConcurrentDictionary TryRemove return false (3 个答案) 关闭 5 年前。 我一直在寻找一种从并发字典
这个问题在这里已经有了答案: How to achieve remove_if functionality in .NET ConcurrentDictionary (5 个答案) 关闭 2 年前。
我只想删除一个值。之后我不需要使用该变量。为什么不包括不需要第二个参数的重载? 我真的只需要将它存储在一个临时局部变量中而不使用它,并让垃圾收集器在方法结束时收集它吗?看起来很傻.. 函数:http:
如果字典不包含给定键的值,它会只返回 false 还是会由于线程竞争条件而返回 false,比如另一个线程添加/更新某些东西? 代码中的问题: ConcurrentDictionary cd = ne
我正在将我的F#代码从dotnet3.1迁移到5,并在以下代码中苦苦挣扎: let tryRemove key (dict: Concurrent.ConcurrentDictiona
本文整理了Java中org.apache.flink.runtime.checkpoint.ZooKeeperCompletedCheckpointStore.tryRemove()方法的一些代码示例
我有一个由元素组成的缓存,每个元素都包含两个并发字典,我认为它们可能是我应用程序中内存泄漏的原因。我经常从这本词典中添加和删除内容。有人可以向我描述并发字典的内存分配如何工作以及我的最佳实践是什么吗?
我相信这是可行的,我已经用多个并发线程对其进行了测试(尽管对于竞争条件和死锁没有详尽无遗): public static System.Collections.Concurrent.Concurren
我是一名优秀的程序员,十分优秀!