Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection was modified, enumeration operation may not execute

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?

like image 216
PATO7 Avatar asked Mar 29 '12 12:03

PATO7


2 Answers

Try to read a clone of your collection

foreach (GMapMarker m in Markers.Copy())
{
   ...
}

this will create a new copy of your collection that will not be affected by another thread but may cause a performance issue in case of huge collection.

So I think it will be better if you locked the collection while reading and writing processes.

like image 71
Amir Ismail Avatar answered Oct 23 '22 02:10

Amir Ismail


You need to lock both on the reading and the writing side. Otherwise one of the threads will not know about the lock and will try to read/modify the collection, while the other is modifying/reading (respectively) with the lock held

like image 22
Attila Avatar answered Oct 23 '22 01:10

Attila