. Advertisement .
..3..
. Advertisement .
..4..
I get the error: invalidoperationexception: collection was modified; enumeration operation may not execute. when I try to run the program below:
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class SubscriptionServer : ISubscriptionServer
{
private static IDictionary<Guid, Subscriber> subscribers;
public SubscriptionServer()
{
subscribers = new Dictionary<Guid, Subscriber>();
}
public void NotifySubscribers(DataRecord sr)
{
foreach(Subscriber s in subscribers.Values)
{
try
{
s.Callback.SignalData(sr);
}
catch (Exception e)
{
DCS.WriteToApplicationLog(e.Message,
System.Diagnostics.EventLogEntryType.Error);
UnsubscribeEvent(s.ClientId);
}
}
}
public Guid SubscribeEvent(string clientDescription)
{
Subscriber subscriber = new Subscriber();
subscriber.Callback = OperationContext.Current.
GetCallbackChannel<IDCSCallback>();
subscribers.Add(subscriber.ClientId, subscriber);
return subscriber.ClientId;
}
public void UnsubscribeEvent(Guid clientId)
{
try
{
subscribers.Remove(clientId);
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine("Unsubscribe Error " +
e.Message);
}
}
}
The error appears the system notifies as follows:
Collection was modified; enumeration operation may not execute
I tried to solve it with another sample. I got the reference in the community forum, but it still returned an invalid result. If someone knows the solution, please give me the support. Thanks!
The cause:
SignalData
is most likely modifying the subscribers dictionary invisibly under the hood during the loop, resulting in that message.The solution: You can solve this problem by changing:
To
Unsubscribe a subscriber to change the contents of the Collection of Subscribers during Enumeration.
This can be fixed in a number of ways, including changing the for loop to use an explicitly
.ToList()