我相信这是有效的,我已经用多个并发线程测试了它(虽然对于竞争条件和死锁而言并非详尽无遗):
public static System.Collections.Concurrent.ConcurrentDictionary<string, item> dict =
new System.Collections.Concurrent.ConcurrentDictionary<string, item>();
public static item dump;
Run Code Online (Sandbox Code Playgroud)
...
foreach (System.Collections.Generic.KeyValuePair<string, item> x in dict)
{
lock (x.Value)
{
if (x.Value.IsCompleted)
{
dict.TryRemove(x.Key, out dump);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个问题是这个问题的延续:
我可以从该字典的枚举循环中删除ConcurrentDictionary中的项吗?
这个问题:
在那我做两个"冒险"的演习:
ConcurrentDictionary时间内删除值,同时枚举它(这似乎没问题).Value一部分ConcurrentDictionary.必要的是因为操纵值的字段不是线程安全的,只是操纵线程安全的值本身ConcurrentDictionary(上面的代码是一个更大的代码块的片段,其中实际操作值的字段).