并行字典正确使用

我正确地认为这是一个并行字典的正确使用

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; 

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

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

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

ConcurrentDictionary<TKey, TValue>是为multithreading场景devise的。 您不必在代码中使用锁来添加或删除集合中的项目。 但是,一个线程总是可以检索一个值,而另一个线程通过给同一个键一个新的值立即更新集合。

因此,可能会得到字典中项目的值不一致的视图

你是对的。

那么在一个线程上枚举字典而在另一个线程上改变字典的可能性是这个类的唯一存在方式。

最好的方法是查看MSDN文档。

对于ConcurrentDictionary,该页面是http://msdn.microsoft.com/en-us/library/dd287191.aspx

在线程安全部分,声明“ConcurrentDictionary(TKey,TValue)的所有公共和受保护成员都是线程安全的,可以从多个线程同时使用。

所以从并发的angular度来看,你没事。

这取决于,在我的情况下,我更喜欢使用这种方法。

 ConcurrentDictionary<TKey, TValue>.AddOrUpdate Method (TKey, Func<TKey, TValue>, Func<TKey, TValue, TValue>); 

有关方法使用详细信息,请参阅MSDN Library 。

示例用法:

 results.AddOrUpdate( Id, id => new DbResult() { Id = id, Value = row.Value, Rank = 1 }, (id, v) => { v.Rank++; return v; });