问 题
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