小编cir*_*are的帖子

C#.NET 4.0 ConcurrentDictionary:一个锁中的TryRemove?

我相信这是有效的,我已经用多个并发线程测试了它(虽然对于竞争条件和死锁而言并非详尽无遗):

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中的值字段

在那我做两个"冒险"的演习:

  1. 从一段ConcurrentDictionary时间内删除值,同时枚举它(这似乎没问题).
  2. 锁定Value一部分ConcurrentDictionary.必要的是因为操纵值的字段不是线程安全的,只是操纵线程安全的值本身ConcurrentDictionary(上面的代码是一个更大的代码块的片段,其中实际操作值的字段).

c# multithreading locking .net-4.0

5
推荐指数
1
解决办法
3723
查看次数

标签 统计

.net-4.0 ×1

c# ×1

locking ×1

multithreading ×1