I can\'t get to the bottom of this error, because when the debugger is attached, it does not seem to occur.
Collection was modified; enumeration operatio
You can copy subscribers dictionary object to a same type of temporary dictionary object and then iterate the temporary dictionary object using foreach loop.
What's likely happening is that SignalData
is indirectly changing the subscribers dictionary under the hood during the loop and leading to that message. You can verify this by changing
foreach(Subscriber s in subscribers.Values)
To
foreach(Subscriber s in subscribers.Values.ToList())
If I'm right, the problem will disappear.
Calling subscribers.Values.ToList()
copies the values of subscribers.Values
to a separate list at the start of the foreach
. Nothing else has access to this list (it doesn't even have a variable name!), so nothing can modify it inside the loop.
You can also lock your subscribers dictionary to prevent it from being modified whenever its being looped:
lock (subscribers)
{
foreach (var subscriber in subscribers)
{
//do something
}
}
I had the same issue, and it was solved when I used a for
loop instead of foreach
.
// foreach (var item in itemsToBeLast)
for (int i = 0; i < itemsToBeLast.Count; i++)
{
var matchingItem = itemsToBeLast.FirstOrDefault(item => item.Detach);
if (matchingItem != null)
{
itemsToBeLast.Remove(matchingItem);
continue;
}
allItems.Add(itemsToBeLast[i]);// (attachDetachItem);
}