I have a Dictionary<int, bool>
I had a InvalidOperationException collection was modified error that was handled but baffled me why.
The only code I can think it is, is the below:
lock (lockObject)
{
AllowInputs[InputNumber] = true;
}
if (AllowInputs.Values.All(x => x == true))
{
//Do stuff
}
If one thread is within the lock statement modifying a value and another thread is executing the All(x => x == true) will this cause the "Collection was modified" errror?
Yes, you need to lock (on the same object) both when you read and when you write. The call to
Allinternally iterates over all the items in the dictionary. If the dictionary is modified by another thread the iterator becomes invalid and an exception is thrown.Try this: