在多线程应用程序中,我必须实现 ConcurrentDictionary<string,Queue<MyClass>>;
队列是否需要是 ConcurrentQueue
?有必要吗?我会将同一个线程中的所有元素出队,所以我认为不会。我对吗?
编辑:我没有提到我在排队的不同线程中排队,所以我认为正确的结构是
Dictionary<string,ConcurrentQueue<MyClass>>
.字典键仅在启动时编辑
最佳答案
如果您只更改 updateValueFactory
中的队列委托(delegate)传递给 AddOrUpdate()
调用并发字典,那么你保证 Queue
对象一次只能被一个线程访问,所以是的,在那种情况下你不需要使用 ConcurrentQueue
例如,以下代码将允许 Enqueue()
和 Dequeue()
随时被许多不同的线程调用,并将阻止任何个人 Queue
ConcurrentDictionary
中的对象一次被多个线程访问:
private static ConcurrentDictionary<string, Queue<string>> dict;
public static void Main()
{
dict = new ConcurrentDictionary<string, Queue<string>>();
}
// If I do this on one thread...
private static void Enqueue(string key, string value)
{
dict.AddOrUpdate(
key,
k => new Queue<string>(new[] { value }),
(k, q) =>
{
q.Enqueue(value);
return q;
});
}
// And I do this on another thread...
private static string Dequeue(string key)
{
string result = null;
dict.AddOrUpdate(
"key",
k => new Queue<string>(),
(k, q) =>
{
result = q.Dequeue();
return q;
});
return result;
}
关于c# - 并发子结构是否需要并发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32391970/