Concurrent Dictionary Correct Usage

前端 未结 5 928
名媛妹妹
名媛妹妹 2020-12-13 05:27

Am I right in thinking this is the correct use of a Concurrent Dictionary

private ConcurrentDictionary myDic = new ConcurrentDictionary

        
相关标签:
5条回答
  • 2020-12-13 05:51

    It depends, in my case I prefer using this method.

    ConcurrentDictionary<TKey, TValue>.AddOrUpdate Method (TKey, Func<TKey, TValue>, Func<TKey, TValue, TValue>);
    

    See MSDN Library for method usage details.

    Sample usage:

    results.AddOrUpdate(
      Id,
      id => new DbResult() {
         Id = id,
         Value = row.Value,
         Rank = 1
      },
      (id, v) =>
      {
         v.Rank++;
         return v;
      });
    
    0 讨论(0)
  • 2020-12-13 05:56

    It depends on what you mean by thread-safe.

    From MSDN - How to: Add and Remove Items from a ConcurrentDictionary:

    ConcurrentDictionary<TKey, TValue> is designed for multithreaded scenarios. You do not have to use locks in your code to add or remove items from the collection. However, it is always possible for one thread to retrieve a value, and another thread to immediately update the collection by giving the same key a new value.

    So, it is possible to get an inconsistent view of the value of an item in the dictionary.

    0 讨论(0)
  • 2020-12-13 05:56

    Yes, you are right.

    That and the possibility to enumerate the dictionary on one thread while changing it on another thread are the only means of existence for that class.

    0 讨论(0)
  • 2020-12-13 05:58

    Best way to find this out is check MSDN documentation.

    For ConcurrentDictionary the page is http://msdn.microsoft.com/en-us/library/dd287191.aspx

    Under thread safety section, it is stated "All public and protected members of ConcurrentDictionary(Of TKey, TValue) are thread-safe and may be used concurrently from multiple threads."

    So from concurrency point of view you are okay.

    0 讨论(0)
  • 2020-12-13 06:02

    Just a note: Does not justify using a ConcurrentDicitonary object with a linear loop, making it underutilized. The best alternative is to follow the recommendations of the Microsoft Documentation, as mentioned by Oded using Parallelism, according to the example below:

    Parallel.For(0, 4, i => 
    {
       myDic.TryAdd(i, 0);
    });
    
    0 讨论(0)
提交回复
热议问题