I have the following code:
var actionsToExecute = _messagesToExecute.Where(m => m.CanExecute).ToList();
It runs fine 99% of the time, but every once in a while it will crash with the exception:
Collection was modified; enumeration operation may not execute
I am a bit lost as it seems a bit random. This is the first line in the method. What might cause a lambda expression to throw this exception?
You either need to use lock() around all your references to _messagesToExecute, or you could use something from System.Collections.Concurrent which handle locking the collection internally.
e.g.
or if you’d rather use locking:
then whenever you update the list:
and then when you’re pulling out the list: