我无法找到这个错误的根源,因为当附加调试器时,它似乎没有发生。

修改集合;枚举操作可能无法执行

下面是代码。

这是Windows服务中的WCF服务器。只要有数据事件,服务就会调用NotifySubscribers()方法(随机间隔,但不经常——大约每天800次)。

When a Windows Forms client subscribes, the subscriber ID is added to the subscribers dictionary, and when the client unsubscribes, it is deleted from the dictionary. The error happens when (or after) a client unsubscribes. It appears that the next time the NotifySubscribers() method is called, the foreach() loop fails with the error in the subject line. The method writes the error into the application log as shown in the code below. When a debugger is attached and a client unsubscribes, the code executes fine.

您认为这段代码有问题吗?我需要使字典线程安全吗?

[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);
        }
    }
}

当前回答

其中有一个环节阐述得很好,并给出了解决方案。 尝试一下,如果你有合适的解决方案,请张贴在这里,这样其他人就能理解。 给出的解决方案是可以的,然后像帖子一样,所以其他人可以尝试这些解决方案。

供您参考原始链接:- https://bensonxion.wordpress.com/2012/05/07/serializing-an-ienumerable-produces-collection-was-modified-enumeration-operation-may-not-execute/

当我们使用. net Serialization类来序列化一个对象时,它的定义包含一个Enumerable类型,即。 集合时,你会很容易得到InvalidOperationException,上面写着“集合被修改了; 如果您的代码是在多线程场景下,则枚举操作可能无法执行。 最根本的原因是,序列化类将通过枚举器遍历集合,就像这样, 问题在于在修改集合时尝试遍历它。

第一种解决方案,我们可以简单地使用锁作为同步解决方案来确保这一点 对List对象的操作一次只能从一个线程执行。 显然,你会受到性能惩罚 如果您想序列化该对象的一个集合,那么对于它们中的每一个,都将应用锁。

net 4.0使处理多线程场景变得很方便。 对于这个序列化收集字段的问题,我发现我们可以从ConcurrentQueue(检查MSDN)类中获益, 这是一个线程安全的FIFO集合,并使代码无锁。

使用这个类,在它的简单性中,你需要为你的代码修改的东西是用它替换Collection类型, 使用Enqueue添加一个元素到ConcurrentQueue的末尾,删除那些锁代码。 或者,如果您正在处理的场景确实需要像List这样的集合,那么您将需要更多的代码来将ConcurrentQueue调整到字段中。

顺便说一句,ConcurrentQueue doesnât有一个清除方法,因为底层算法doesnât允许原子地清除集合。 所以你必须自己做,最快的方法是重新创建一个新的空的ConcurrentQueue来替换。

其他回答

我也有同样的问题,当我使用for循环而不是foreach时,它得到了解决。

// foreach (var item in itemsToBeLast)
for (int i = 0; i < itemsToBeLast.Count; i++)
{
    var matchingItem = itemsToBeLast.FirstOrDefault(item => item.Detach);

   if (matchingItem != null)
   {
      itemsToBeLast.Remove(matchingItem);
      continue;
   }
   allItems.Add(itemsToBeLast[i]);// (attachDetachItem);
}

实际上,在我看来,问题似乎是您正在从列表中删除元素,并期望继续读取列表,就像什么都没有发生一样。

你真正需要做的是从头开始,再回到起点。即使您从列表中删除了元素,也可以继续读取它。

其中有一个环节阐述得很好,并给出了解决方案。 尝试一下,如果你有合适的解决方案,请张贴在这里,这样其他人就能理解。 给出的解决方案是可以的,然后像帖子一样,所以其他人可以尝试这些解决方案。

供您参考原始链接:- https://bensonxion.wordpress.com/2012/05/07/serializing-an-ienumerable-produces-collection-was-modified-enumeration-operation-may-not-execute/

当我们使用. net Serialization类来序列化一个对象时,它的定义包含一个Enumerable类型,即。 集合时,你会很容易得到InvalidOperationException,上面写着“集合被修改了; 如果您的代码是在多线程场景下,则枚举操作可能无法执行。 最根本的原因是,序列化类将通过枚举器遍历集合,就像这样, 问题在于在修改集合时尝试遍历它。

第一种解决方案,我们可以简单地使用锁作为同步解决方案来确保这一点 对List对象的操作一次只能从一个线程执行。 显然,你会受到性能惩罚 如果您想序列化该对象的一个集合,那么对于它们中的每一个,都将应用锁。

net 4.0使处理多线程场景变得很方便。 对于这个序列化收集字段的问题,我发现我们可以从ConcurrentQueue(检查MSDN)类中获益, 这是一个线程安全的FIFO集合,并使代码无锁。

使用这个类,在它的简单性中,你需要为你的代码修改的东西是用它替换Collection类型, 使用Enqueue添加一个元素到ConcurrentQueue的末尾,删除那些锁代码。 或者,如果您正在处理的场景确实需要像List这样的集合,那么您将需要更多的代码来将ConcurrentQueue调整到字段中。

顺便说一句,ConcurrentQueue doesnât有一个清除方法,因为底层算法doesnât允许原子地清除集合。 所以你必须自己做,最快的方法是重新创建一个新的空的ConcurrentQueue来替换。

InvalidOperationException - 发生了InvalidOperationException。它报告foreach循环中的“集合被修改”

使用break语句,一旦对象被移除。

ex:

ArrayList list = new ArrayList(); 

foreach (var item in list)
{
    if(condition)
    {
        list.remove(item);
        break;
    }
}

我见过很多这样的选择,但对我来说,这是最好的。

ListItemCollection collection = new ListItemCollection();
        foreach (ListItem item in ListBox1.Items)
        {
            if (item.Selected)
                collection.Add(item);
        }

然后简单地遍历集合。

注意,ListItemCollection可以包含重复项。默认情况下,没有任何东西阻止将副本添加到集合中。为了避免重复,你可以这样做:

ListItemCollection collection = new ListItemCollection();
            foreach (ListItem item in ListBox1.Items)
            {
                if (item.Selected && !collection.Contains(item))
                    collection.Add(item);
            }