最近我有一个需要 https://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice/58079327#58079327 for a Dictionary
我可以从多个线程进行更新,这项工作的明显候选者是内置的ConcurrentDictionary https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2。不幸的是我最终没有使用它,而是使用了普通的Dictionary
保护与一个lock
,因为一个致命的限制:TryRemove https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2.tryremove不提供允许有条件删除元素的重载。可用的TryRemove
方法删除并返回删除的元素,但在我的情况下,只有在同一工作流程之前插入的元素才必须删除该元素。从不同的工作流程中删除元素(即使是一小部分微秒)可能会产生不良后果,我不想解决这些后果。所以我的问题是:是否可以修改现有的ConcurrentDictionary
具有线程安全条件的类TryRemove
扩展方法?
这是我的用例供参考。使用以下方法安全地填充字典AddOrUpdate https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentdictionary-2.addorupdate method:
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?
}