Collection was modified; enumeration operation may not execute

后端 未结 16 2546
南旧
南旧 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:37

    A more efficient way, in my opinion, is to have another list that you declare that you put anything that is "to be removed" into. Then after you finish your main loop (without the .ToList()), you do another loop over the "to be removed" list, removing each entry as it happens. So in your class you add:

    private List toBeRemoved = new List();
    

    Then you change it to:

    public void NotifySubscribers(DataRecord sr)
    {
        toBeRemoved.Clear();
    
        ...your unchanged code skipped...
    
       foreach ( Guid clientId in toBeRemoved )
       {
            try
            {
                subscribers.Remove(clientId);
            }
            catch(Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Unsubscribe Error " + 
                    e.Message);
            }
       }
    }
    
    ...your unchanged code skipped...
    
    public void UnsubscribeEvent(Guid clientId)
    {
        toBeRemoved.Add( clientId );
    }
    

    This will not only solve your problem, it will prevent you from having to keep creating a list from your dictionary, which is expensive if there are a lot of subscribers in there. Assuming the list of subscribers to be removed on any given iteration is lower than the total number in the list, this should be faster. But of course feel free to profile it to be sure that's the case if there's any doubt in your specific usage situation.

提交回复
热议问题