简体   繁体   中英

Does Concurrent substructures needs to be Concurrent?

In a multithreaded application I have to implement a ConcurrentDictionary<string,Queue<MyClass>>; Does the queue need to be a ConcurrentQueue ? Is it necessary? I will dequeue the elements all in the same thread so I think not. Am I right? Edit: I not mentioned that I enqueue in a different thread of where I'm enqueuing so I think the right structure will be Dictionary<string,ConcurrentQueue<MyClass>> . The dictionary keys are edited only at startup

If you only ever alter the queue in the updateValueFactory delegate passed to an AddOrUpdate() call to the concurrent dictionary, then you guarantee that the Queue object is only accessed by one thread at a time, so yes in that case you wouldn't need to use a ConcurrentQueue

For example, the following code would allow Enqueue() and Dequeue() to be called whenever you like by many different threads, and will prevent any individual Queue object in the ConcurrentDictionary from being accessed by more than one thread at a time:

    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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM