首页 > 编程语言 >C# 操作List集合报错:集合被修改,枚举操作可能不会执行(Collection was modified, enumeration operation may not execute)

C# 操作List集合报错:集合被修改,枚举操作可能不会执行(Collection was modified, enumeration operation may not execute)

时间:2023-05-26 11:05:38浏览次数:35  
标签:index execute lock System collection 报错 Markers 集合 problem

问 题
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?
解决方案
This is pretty common mistake - modifying a collection whilst iterating it using foreach, keep in mind that foreach uses readonly IEnumerator instance.
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:
If Markers implements IColletion - lock on SyncRoot:
 
lock (Markers.SyncRoot)
 
Use for():
 
for (int index = 0; index < Markers.Count(); index++)
{
    if (Markers>= Markers.Count())
    {
       // TODO: handle this case to avoid run time exception
    }
}

标签:index,execute,lock,System,collection,报错,Markers,集合,problem
From: https://blog.51cto.com/chengzheng183/6354384

相关文章

  • Java集合互转,集合转换
    集合之间的互转确认JDK是否支持如下集合的转换CollectorsObjects参考:https://blog.csdn.net/winterking3/article/details/116457573List<T>转Map<String,T>PHP:Map<String,T>array_combine(()->T::getXXX,List<T>list);Java:privatestatic<T,......
  • 求一个数所有因子的集合的子集中满足所有数均互质的最大子集
    题意:很明显了,就是把数n的所有因子求出来,在里面挑选一些数,使这些数之间均互质,求这些的最大个数。结论:先讲结论:最大个数为数n的质因数个数加1思路:我们已知一个数的质因数,就可以把这个数表示成若干质因数的乘积,例如:12=2*2*3;其中2,3是12的质因数,表达式中2的个数是2,3的......
  • 编译静态库遇到的 LNK2019 报错
    前文提到了CMake学习文末基本涵盖了我遇到的编译问题,但是在得到一个编译好的.lib文件后,还需要放到项目中引用成功后才算真正的完成静态库的编译嗯,我之所以说这些是因为我在项目中链接静态库时出现了LNK2019经典错误错误如下:Libraryd.lib(at_exit.obj):errorLNK2019:......
  • Swift中常见的String用法,Array高阶使用,Set集合操作
    String字符串常见用法生成字符串创建字符串letgreeting="Hello,world!"letname=String("John")连接字符串:使用加号(+)或者字符串插值(使用())来将多个字符串连接起来。varfirstName="John"letlastName="Doe"letfullName=firstName+""+las......
  • Nvm 安装node报错: The system cannot find the path specified.
    解决思路:1.确保你安装nvm之前node.js已经删除干净了。这一步如果不会请移步:https://blog.csdn.net/m0_51945510/article/details/127710792这个是要删除的。 2.确保你点击的安装路径中,没有空格和中文,并且确定存在这个目录(安装时,不会帮你新建文件夹)。  上面两张图只......
  • Problem F: STL——集合运算
    HomeWebBoardProblemSetStandingStatusStatisticsProblemF:STL——集合运算TimeLimit:1Sec  MemoryLimit:128MBSubmit:3767  Solved:1927[Submit][Status][WebBoard]Description集合的运算就是用给定的集合去指定新的集合。设A和B是集合,则它们的并......
  • 记一次windows装docker,然后nacos连接宿主机mysql报错问题
    之前一直用linux装docker,这两天有空研究下windows上装DockerDesktop。安装步骤就不一一细说了,记录几个容易忘得地方。设置docker镜像存储位置//打包现有镜像wsl--exportdocker-desktop-data"D:\\work\\other-tools\\docker\\docker-desktop-data.tar"//注销镜像wsl--......
  • Python集合 (set) 的增删改查及 copy()方法
    集合是无序的,不重复的数据集合,它里面的元素是可哈希的(不可变类型),但是集合本身是不可哈希(所以集合做不了字典的键)的。以下是集合最重要的两点:1、去重,把一个列表变成集合,就自动去重了。2、关系测试,测试两组数据之前的交集、差集、并集等关系。一、集合的创建set1=set({1,2......
  • The MySQL server is running with the --skip-grant-tables option so it cannot exe
     TheMySQLserverisrunningwiththe--skip-grant-tablesoptionsoitcannotexecutethisstatement 默认情况下,启动MySQL数据库实例期间,会读取所有的权限表条目到内存中,后续被缓存到内存中的权限条目作为依据即刻对后续的控制访问生效(传送门)。使用"skip-grant-tab......
  • c# 集合相关的类
    c#中的队列和栈Queue代表这一个先进先出的对象集合,当你需要对各项进行先进先出访问时,可使用Queue队列。反之使用Stack。不建议将Queue类用于新开发。相反,我们建议使用泛型Queue<T>类。使用ConcurrentQueue<T>或ConcurrentStack<T>如果需要同时从多个线程访问集合。......