Jon
Jon

Reputation: 40032

LINQ and Dictionary Thread Safety

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?

Upvotes: 1

Views: 550

Answers (2)

TehBoyan
TehBoyan

Reputation: 6890

Yes, you need to either lock on the object when you read or write or look into the reader writer pattern that allows you to have one writer and multiple readers:

that is, if you are performing multiple reads on the same object.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 837916

Yes, you need to lock (on the same object) both when you read and when you write. The call to All internally 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:

lock (lockObject)
{
    if (AllowInputs.Values.All(x => x == true))
    {
      //Do stuff
    }
}

Upvotes: 3

Related Questions