Collection was modified; enumeration operation may not execute

后端 未结 16 2555
南旧
南旧 2020-11-21 06:05

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

16条回答
  •  日久生厌
    2020-11-21 06:50

    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.

提交回复
热议问题