Using lock on the key of a Dictionary

后端 未结 7 1022
被撕碎了的回忆
被撕碎了的回忆 2021-02-15 17:18

I have a Dictionary.

EDIT: It was pointed out to me, that my example was bad. My whole intention was not to update the references

7条回答
  •  借酒劲吻你
    2021-02-15 18:06

    In your example, you can not do what you want to do!

    You will get a System.InvalidOperationException with a message of Collection was modified; enumeration operation may not execute.

    Here is an example to prove:

    using System.Collections.Generic;
    using System;
    
    public class Test
    {
        private Int32 age = 42;
    
        static public void Main()
        {
           (new Test()).TestMethod();
        }
    
        public void TestMethod()
        {
            Dictionary myDict = new Dictionary();
    
            myDict[age] = age.ToString();
    
            foreach(KeyValuePair pair in myDict)
            {
                Console.WriteLine("{0} : {1}", pair.Key, pair.Value);
                ++age;
                Console.WriteLine("{0} : {1}", pair.Key, pair.Value);
                myDict[pair.Key] = "new";
                Console.WriteLine("Changed!");
            }
        }   
    }
    

    The output would be:

    42 : 42
    42 : 42
    
    Unhandled Exception: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
       at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()
       at Test.TestMethod()
       at Test.Main()
    

提交回复
热议问题