I have a Dictionary of type (int, < T >).
I have a helper method GetAll(); that gets me all the values as IEnumerable< T >.
I sometimes get an exception When I try to use a lambda expression to search for a value, Like this:
myDictionary.GetAll().Where(x => x.Id == myID)
The search condition is valid and it exists.
The exception I get is:
System.InvalidOperationException: Collection was modified;
enumeration operation may not execute.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.ValueCollection.Enumerator.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource]
(IEnumerable`1 source, Func`2 predicate)
I checked and found that using ToList() might resolve my problem. I tried, but the issue reoccurred. Can anyone help?
EDIT - Dictionary is being called/shared by multiple threads/functions/classes simultaneously. Putting in a lock would be painful and have performance overheads. The issue is rare and random to reproduce.
EDIT2 : Used ToList(), doesn't help. Here's the GetAll method : It does use the Values internally, just has a lock object wrapped over it.
public IEnumerable<U> GetAll()
{
IEnumerable<U> values;
lock (lockObj)
{
values = myDictionary.Values;
}
return values;
}