c# - 并发子结构是否需要并发?

标签 c# multithreading data-structures concurrency

在多线程应用程序中,我必须实现 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/

相关文章:

c# - 内存不足的图片框

c# - AspNetCore 集成测试多个 WebApplicationFactory 实例?

c++ - 什么时候初始化 `thread_local` 全局变量?

java - 使用鼠标在两点之间移动

python - 删除 pandas DataFrame 中的嵌套数组

algorithm - 找出液体到达第 n 个杯子所需的时间

c++ - C++中的map数据结构是什么

c# - 如何在 C# 中调用 Azure Rest API

c# - 为什么在 c# 项目目录中的 x86 文件夹?

python - PyQt5 QObject : Cannot create children for a parent that is in a different thread