【发布时间】:2010-06-21 11:22:01
【问题描述】:
我相信这是可行的,我已经使用多个并发线程对其进行了测试(尽管对于竞争条件和死锁来说并不详尽):
public static System.Collections.Concurrent.ConcurrentDictionary<string, item> dict =
new System.Collections.Concurrent.ConcurrentDictionary<string, item>();
public static item dump;
...
foreach (System.Collections.Generic.KeyValuePair<string, item> x in dict)
{
lock (x.Value)
{
if (x.Value.IsCompleted)
{
dict.TryRemove(x.Key, out dump);
}
}
}
这个问题是这个问题的延续:
Can I remove items from a ConcurrentDictionary from within an enumeration loop of that dictionary?
还有这个问题:
Updating fields of values in a ConcurrentDictionary
我正在做两个“冒险”的动作:
- 从
ConcurrentDictionary中删除值,同时枚举它(这似乎没问题)。 - 锁定
ConcurrentDictionary的Value部分。必要,因为操作值的字段不是线程安全的,只有操作ConcurrentDictionary的值本身是线程安全的(上面的代码是一个更大的代码块的 sn-p,其中实际操作了值的字段)。
【问题讨论】:
标签: c# multithreading .net-4.0 locking