【发布时间】:2015-03-18 14:18:58
【问题描述】:
这样更好吗:
public void Test()
{
ConcurrentDictionary<int, string> dictionary = new ConcurrentDictionary<int, string>();
dictionary.TryAdd(0, "A");
dictionary.TryAdd(1, "B");
dictionary.TryAdd(2, "A");
dictionary.TryAdd(3, "D");
foreach (var item in dictionary)
{
string foundItem;
if (dictionary.TryGetValue(item.Key, out foundItem))
{
if (foundItem == "A")
{
if (dictionary.TryRemove(item.Key, out foundItem))
{
// Success
}
}
}
}
}
比这个?:
public void Test2()
{
ConcurrentDictionary<int, string> dictionary = new ConcurrentDictionary<int, string>();
dictionary.TryAdd(0, "A");
dictionary.TryAdd(1, "B");
dictionary.TryAdd(2, "A");
dictionary.TryAdd(3, "D");
foreach (var item in dictionary)
{
string foundItem;
if (item.Value == "A")
{
if (dictionary.TryRemove(item.Key, out foundItem))
{
// Success
}
}
}
}
这个方法会被多个线程访问。
我的困惑是,每当我想删除一个项目时,我都会尝试先获取它,然后再删除它。但首先,我使用了foreach 循环,这意味着我已经得到了该项目。任何想法将不胜感激。
【问题讨论】:
-
第一个选项没有意义。当你已经有一件物品时,你为什么还要打电话给
TryGetValue:? -
我使用
TryGetValue因为我在想我可能会得到一个过时的值... :) -
如果某个线程在您调用
TryGetValue之后但在您调用TryRemove之前修改了值怎么办?仍然有一场比赛:) -
我认为
TryGeValue会阻止其他方法,例如TryRemove。不是这样吗? -
它可能在内部锁定(或无锁定)。但是我说的是当某个线程在
TryGeValue返回之后,但在调用TryRemove之前修改值时会发生什么。想想看。我会选择第二个选项或 Jon 在下面的答案,
标签: c# dictionary concurrency