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
The accepted answer is imprecise and incorrect in the worst case . If changes are made during ToList()
, you can still end up with an error. Besides lock
, which performance and thread-safety needs to be taken into consideration if you have a public member, a proper solution can be using immutable types.
In general, an immutable type means that you can't change the state of it once created. So your code should look like:
public class SubscriptionServer : ISubscriptionServer
{
private static ImmutableDictionary subscribers = ImmutableDictionary.Empty;
public void SubscribeEvent(string id)
{
subscribers = subscribers.Add(Guid.NewGuid(), new Subscriber());
}
public void NotifyEvent()
{
foreach(var sub in subscribers.Values)
{
//.....This is always safe
}
}
//.........
}
This can be especially useful if you have a public member. Other classes can always foreach
on the immutable types without worrying about the collection being modified.