Adding to a generic dictionary causes IndexOutOfRangeException

前端 未结 3 1280
孤城傲影
孤城傲影 2021-02-03 21:05

I\'m using a dictionary inside of some Task.

Logically I have set it up so that my Keys will never clash, though sometimes when I am adding to the dictionary I get this

3条回答
  •  悲哀的现实
    2021-02-03 21:14

    Your issue is most likely synchronization. When a Dictionary is added to it sometimes needs to increase the size of the underlying structure (an array). If you are adding from multiple threads that may result in an IndexOutOfRangeException. You need to use locks etc. to make sure you are adding in a safe way.

    Alternatively you can use a ConcurrentDictionary which is a thread-safe collection.

提交回复
热议问题