并发字典正确使用 [英] Concurrent Dictionary Correct Usage

查看:175
本文介绍了并发字典正确使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是正确的思维,这是正确的使用并发字典

Am I right in thinking this is the correct use of a Concurrent Dictionary

private ConcurrentDictionary<int,long> myDic = new ConcurrentDictionary<int,long>();

//Main thread at program startup

for(int i = 0; i < 4; i++)
{
  myDic.Add(i, 0);
}

//Seperate threads use this to update a value

myDic[InputID] = newLongValue;

我没有锁等和我只是更新在字典中,即使多个线程可能会试图做同样的价值。

I have no locks etc and am just updating the value in the dictionary even though multiple threads might be trying to do the same.

推荐答案

这取决于你所说的线程安全的意思。

It depends on what you mean by thread-safe.

从MSDN - 如何:添加和删除项目从ConcurrentDictionary

From MSDN - How to: Add and Remove Items from a ConcurrentDictionary:

ConcurrentDictionary&LT; TKEY的,TValue&GT; 是专为多线程方案。您不必使用锁在code从集合添加或删除项目。然而,它始终是可能的一个线程来检索一个值,和另一个线程来给予相同的密钥的新值立即更新集合

ConcurrentDictionary<TKey, TValue> is designed for multithreaded scenarios. You do not have to use locks in your code to add or remove items from the collection. However, it is always possible for one thread to retrieve a value, and another thread to immediately update the collection by giving the same key a new value.

因此​​,有可能得到一个项目在字典中的值的不一致的视图

So, it is possible to get an inconsistent view of the value of an item in the dictionary.

这篇关于并发字典正确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆