c# ConcurrentDictionary和ConcurrentQueue怎么使用?

2019-12-23 13:13发布

问题:


上图是我的数据结构。我定义了一个线程安全的静态变量(作用:消息队列)用来存储消息,如下:

private static ConcurrentDictionary<string, ConcurrentQueue<SignalModel>> _dic = new ConcurrentDictionary<string, ConcurrentQueue<SignalModel>>();

既用到了ConcurrentDictionary又用到了ConcurrentQueue。用字典是因为要根据IP分组存储。

我就是不知道用了ConcurrentDictionary之后,字典的value是否还有必要使用ConcurrentQueue来定义。

是否应该将ConcurrentQueue改成List?

回答1:

参考 Concurrent collections is it safe to modify from different threads:

ConcurrentQueue is only ensuring that calls to methods of that class are observed to be atomic; it is making no other guarantees surrounding thread safety.