When should I use ConcurrentDictionary and Dictionary?

前端 未结 4 1064
余生分开走
余生分开走 2021-02-01 01:05

I\'m always confused on which one of these to pick. As I see it I use Dictionary over List if I want two data types as a Key and Val

4条回答
  •  南旧
    南旧 (楼主)
    2021-02-01 01:23

    "Use ConcurrentDictionary if you use your dictionary a lot in code" is kind of vague advice. I don't blame you for the confusion.

    ConcurrentDictionary is primarily for use in an environment where you're updating the dictionary from multiple threads (or async tasks). You can use a standard Dictionary from as much code as you like if it's from a single thread ;)

    If you look at the methods on a ConcurrentDictionary, you'll spot some interesting methods like TryAdd, TryGetValue, TryUpdate, and TryRemove.

    For example, consider a typical pattern you might see for working with a normal Dictionary class.

    // There are better ways to do this... but we need an example ;)
    if (!dictionary.ContainsKey(id))
        dictionary.Add(id, value);
    

    This has an issue in that between the check for whether it contains a key and calling Add a different thread could call Add with that same id. When this thread calls Add, it'll throw an exception. The method TryAdd handles that for you and will return a true/false telling you whether it added it (or whether that key was already in the dictionary).

    So unless you're working in a multi-threaded section of code, you probably can just use the standard Dictionary class. That being said, you could theoretically have locks to prevent concurrent access to a dictionary; that question is already addressed in "Dictionary locking vs. ConcurrentDictionary".

提交回复
热议问题