Programmers learn & share
0 votes
27 views

Problem :

I am unable to understand the root cause of following error, because when I attach the debugger it will not occur.

Invalid operation exception: collection was modified; enumeration operation may not execute.                

This is the WCF server in a Window based service. The method NotifySubscribers() is always called by the service whenever there is a data event. When a Windows Forms client subscribes to it, then the subscriber ID is added to the subscribers dictionary, and when the client un subscribes, the ID is deleted from the dictionary. The error seems to happen when the client unsubscribes. When the next time the NotifySubscribers() method is called, the foreach() loop will fail with the error in the subject line. But when the debugger is attached and the client unsubscribes, the code executes fine.

Do you see a problem in my code? Do I need to make the dictionary the thread-safe?

by (7.5k points)   | 27 views

1 Answer

0 votes

Solution :

I think that the SignalData is indirectly changing the subscribers dictionary under the hood during the loop and leading this is leading to that message. You can cross check it by changing

foreach(Subscriber s in subscribers.Values)

To

foreach(Subscriber s in subscribers.Values.ToList())

If I am not wrong after doing above changes your problem will disappear.

by (36.1k points)  
2,245 questions
2,807 answers
60 comments
241 users