Updating fields of values in a ConcurrentDictionary

后端 未结 3 1415
执笔经年
执笔经年 2020-12-18 22:33

I am trying to update entries in a ConcurrentDictionary something like this:

class Class1
{
    public int Counter { get; set; }
}

class Test
{
    private          


        
3条回答
  •  北海茫月
    2020-12-18 23:12

    First, to solve your locking problem:

    class Class1
    {
        // this must be a variable so that we can pass it by ref into Interlocked.Increment.
        private int counter;
    
        public int Counter
        {
            get{return counter; }
        }
    
        public void Increment()
        {
            // this is about as thread safe as you can get.
            // From MSDN: Increments a specified variable and stores the result, as an atomic operation.
            Interlocked.Increment(ref counter);
    
            // you can return the result of Increment if you want the new value,
            //but DO NOT set the counter to the result :[i.e. counter = Interlocked.Increment(ref counter);] This will break the atomicity.
        }
    }
    

    Iterating the just values should be faster than iterating the key value pair. [Though I think iterating a list of keys and doing the look-ups will be faster still on the ConcurrentDictionary in most situations.]

    class Test
    {
        private ConcurrentDictionary dictionary = new ConcurrentDictionary();
    
        public void TestIt()
        {
            foreach (var foo in dictionary.Values)
            {
                foo.Increment();
            }
        }
    
        public void TestItParallel()
        {
            Parallel.ForEach(dictionary.Values,x=>x.Increment() );
        }
    
    }
    

提交回复
热议问题