小编nop*_*nop的帖子

在ConcurrentDictionary中AddOrUpdate线程安全吗?

我试图在ConcurrentDictionary中使用AddOrUpdate方法。

从此页面上的“备注”部分https://msdn.microsoft.com/zh-cn/library/dd287191(v=vs.110).aspx。它说

“但是,这些方法的委托在锁之外调用,以避免在锁下执行未知代码可能引起的问题。因此,这些委托执行的代码不受操作原子性的约束。”

所以我不确定它是否是线程安全的。我有一种情况,如果找不到键,则值为1,否则将值增加1。

我写下面的功能

    private static void AddOrUpdate(ConcurrentDictionary<string, int> map)
    {
        Random r = new Random();
        Thread.Sleep(r.Next(10));
        map.AddOrUpdate(Key, 1, (key, value) => value + 1);
    }

    public static void TestThreadSafe(ConcurrentDictionary<string, int> map)
    {
        Thread[] threads = new Thread[Size];
        for (int i = 0; i < Size; ++i)
        {
            threads[i] = new Thread(() => AddOrUpdate(map));
        }

        foreach (var thread in threads)
        {
            thread.Start();
        }
    }
Run Code Online (Sandbox Code Playgroud)

创建了约300,000个线程并并行运行它们。结果始终为300,000。

以上方法线程安全吗?什么时候AddOrUpdate不安全线程?

c# multithreading

4
推荐指数
1
解决办法
2814
查看次数

标签 统计

c# ×1

multithreading ×1