集合被修改,枚举操作可能不会执行 [英] Collection was modified, enumeration operation may not execute

查看:986
本文介绍了集合被修改,枚举操作可能不会执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的多线程应用程序,我得到这个错误

I have multithreads application and i get this error

************** Exception Text **************
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
   at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
   at System.Collections.Generic.List`1.Enumerator.MoveNext()
   ...

我可能有我收藏的问题,因为。一个线程我读我的收集和在另一个线程我收集修改

I probably have problem with my collection, because on one thread i read my collection and on another thread i modify collection.

public readonly ObservableCollectionThreadSafe<GMapMarker> Markers = new ObservableCollectionThreadSafe<GMapMarker>();


public void problem()
{
  foreach (GMapMarker m in Markers)
  {
    ...
  }
}

我想使用此代码锁定集合,但不起作用。

I am trying to lock collection with this code, but doesn't work.

public void problem()
    {
       lock(Markers)
       {
         foreach (GMapMarker m in Markers)
         {
           ...
         }
       }
    }

任何想法来解决这个问题?

Any ideas to fix that problem?

推荐答案

这是很常见错误 - 修改的集合,同时使用的foreach 迭代它,记住,的foreach 使用只读 IEnumerator的实例。

This is pretty common mistake - modifying a collection whilst iterating it using foreach, keep in mind that foreach uses readonly IEnumerator instance.

试用使用通过收集循环为()额外指数检查,以便如果索引越界 - 你就可以申请额外的逻辑来处理这个问题,也可作为循环退出条件,你可以使用LINQ 计数()这将评估计数每次如果底层枚举不执行的ICollection 值:

Try out loop through the collection using for() with extra index check so if index is out of bound - you would be able applying additional logic to handle this, also as loop exit condition you can use LINQ Count() which would evaluate count value each time if underlying enumeration does not implement ICollection:

如果标记工具 IColletion - 上SyncRoot上的锁:

If Markers implements IColletion - lock on SyncRoot:

lock (Markers.SyncRoot)

使用为()

for (int index = 0; index < Markers.Count(); index++)
{
    if (Markers>= Markers.Count())
    {
       // TODO: handle this case to avoid run time exception
    }
}

可能会发现这个帖子有用:的如何foreach循环在C#中工作?

Might find this post useful: How do foreach loops work in C#?

这篇关于集合被修改,枚举操作可能不会执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆