相关疑难解决方法(0)

ConcurrentDictionary陷阱 - 来自GetOrAdd和AddOrUpdate的委托工厂是否同步?

文档ConcurrentDictionary没有明确的状态,所以我想我们不能指望委托valueFactoryupdateValueFactory让它们的执行同步(分别来自GetOrAdd()和AddOrUpdate()操作).

因此,我认为我们无法在其中实现需要并发控制的资源,而无需手动实现我们自己的并发控制,可能只是使用[MethodImpl(MethodImplOptions.Synchronized)]代理.

我对吗?或者ConcurrentDictionary是线程安全的事实,我们可以预期对这些代理的调用会自动同步(线程安全)?

.net c# concurrency multithreading thread-safety

33
推荐指数
2
解决办法
1万
查看次数

ConcurrentDictionary的乐观并发Remove方法

我在ConcurrentDictionary中寻找一个方法,允许我按键删除一个条目,当且仅当该值等于我指定的值时,类似于TryUpdate,但是对于删除.

执行此操作的唯一方法似乎是此方法:

ICollection<KeyValuePair<K, V>>.Remove(KeyValuePair<K, V> keyValuePair)
Run Code Online (Sandbox Code Playgroud)

它是ICollection接口的显式实现,换句话说,我必须首先将ConcurrentDictionary转换为ICollection,以便我可以调用Remove.

删除完全符合我的要求,并且该投射也没什么大不了的,源代码也显示它调用私有方法TryRemovalInternal与bool matchValue = true,所以它看起来都很漂亮和干净.

然而,令我担心的是,它没有被记录为ConcurrentDictionary的乐观并发Remove方法,因此http://msdn.microsoft.com/en-us/library/dd287153.aspx只是重复ICollection样板,并且该如何从一个ConcurrentDictionary添加和删除的项目并不要么提到的方法.

有谁知道这是否可行,或者是否有其他方法我缺席?

.net optimistic-concurrency

7
推荐指数
1
解决办法
922
查看次数

ConcurrentDictionary GetOr添加异步

我想使用诸如GetOrAdda之类的东西ConcurrentDictionary作为Web服务的缓存。该词典有异步版本吗?GetOrAdd将使用发出Web请求HttpClient,因此,如果该词典的某个版本中GetOrAdd是异步的,那就太好了。

为了消除混淆,字典的内容将是对Web服务的调用的响应。

ConcurrentDictionary<string, Response> _cache = new ConcurrentDictionary<string, Response>();



var response = _cache.GetOrAdd("id", (x) => { _httpClient.GetAsync(x).GetAwaiter().GetResponse();} )
Run Code Online (Sandbox Code Playgroud)

.net c# .net-core .net-core-2.2

6
推荐指数
4
解决办法
1183
查看次数

TryRemove来自C#中ConcurrentDictionary的键值对

我的场景是我想要一个ConcurrentDictionary像这样的方法.

bool TryRemove(TKey key, TValue value) {
    // remove the value IF the value passed in == dictionary[key]
    // return false if the key is not in the dictionary, or the value is not equal
}
Run Code Online (Sandbox Code Playgroud)

有没有办法同时做到这一点?我很难找到这个场景的答案,尽管看起来这是一个常见的用例.

我可以做这样的事情,但如果我已经使用了,我想避免锁定ConcurrentDictionary.我还必须锁定GetOrAdd()AddOrUpdate()在其他地方打电话.似乎应该有一个更好的方法ConcurrentDictionary.

ConcurrentDictionary<int, string> dict = ...;

/// stuff

int keyTryToRemove = 1337;
string valTryToRemove = "someValue";

bool success = false;
lock(keyTryToRemove) {
    string val;
    if (dict.TryRemove(keyTryToRemove, out val)) {
        if (val == valTryToRemove) …
Run Code Online (Sandbox Code Playgroud)

c# concurrency concurrentdictionary

3
推荐指数
1
解决办法
1006
查看次数