I have this code which is being run every frame of a game:
foreach (var repeaterAction in conditionTimes.Keys)
{
if (repeaterAction.Condition() == true)
{
if (conditionTimes[repeaterAction] == TimeSpan.Zero)
{
repeaterAction.Action();
}
else if (conditionTimes[repeaterAction] >= repeaterAction.InitialLapse)
{
repeaterAction.Action();
conditionTimes[repeaterAction] -= repeaterAction.ActionInterval;
}
conditionTimes[repeaterAction] += gameTime.ElapsedGameTime;
}
else
{
conditionTimes[repeaterAction] = TimeSpan.Zero;
}
}
This is giving me the following error:
Collection was modified; enumeration operation may not execute.
Is there a way to modify the value in the key-value pair inside the foreach loop, without copying the Dictionary every frame?
I'm Advising against trying to modify a collection while looping through it with dictionaries however it is possible since direct key access is available. Just add .ToArray()
after the conditionTimes.Keys
in the foreach
then the keys becomes a separate collection and you can modify the dictionary:
foreach (var repeaterAction in conditionTimes.Keys.ToArray())
{
if (repeaterAction.Condition() == true)
{
if (conditionTimes[repeaterAction] == TimeSpan.Zero)
{
repeaterAction.Action();
}
else if (conditionTimes[repeaterAction] >= repeaterAction.InitialLapse)
{
repeaterAction.Action();
conditionTimes[repeaterAction] -= repeaterAction.ActionInterval;
}
conditionTimes[repeaterAction] += gameTime.ElapsedGameTime;
}
else
{
conditionTimes[repeaterAction] = TimeSpan.Zero;
}
}
You also have to modify you're code so that if the key changes you actually remove an entry from your dictionary and add the new one, because keys really cant be changed, just removed.
Again this is not recommended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With