I know that I can’t modify a collection while iterating over it.
Normally I make a copy of the collection I want to iterate over, then iterate over the copy to avoid errors.
My program; however, makes lots of fast modifications to the collection I’m trying to make a copy of.
Could the error be occurring because I am making a copy while the parent collection is being modified?
I know ConcurrentDictionary provides some sort of locking mechanism for cross threading. Is there something similar I can use to prevent this error?
// Original collection:
Dictionary<string, Enemy> Dict_Enemies = new Dictionary<string, Enemy>();
// Copy of original collection: (this line throws the exception)
Dictionary<string, Enemy> Dict_Enemies_Copy = new Dictionary<string, Enemy>(Dict_Enemies);
Try using a ConcurrentDictionary for
Dict_Enemiesto allow it to be modified from multiple threads. Then make a copy of it in a thread-safe operation using the ToArray() method: