Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why SynchronizedCollection<T> does not lock on IEnumerable.GetEnumerator()

Tags:

c#-3.0

Why SynchronizedCollection<T> does not acquire a lock on SyncObj in explicit implementation of IEnumerable.GetEnumerator()

  IEnumerator IEnumerable.GetEnumerator()
    {
        return this.items.GetEnumerator();
    }

Implicit implementation does acquire a lock on SyncOb (verified by reflector).

It could be problem during foreach loop on this collection. One thread might have acquired a lock and the other could try to read it using foreach?

like image 468
Deepak Avatar asked Dec 16 '09 21:12

Deepak


1 Answers

Because there is no way for the class to know when the client code is done using the iterator. Which is one reason that the MSDN Library docs on the System.Collection classes always warn that iterating a collection isn't thread-safe.

Although they appeared to have forgotten to mention that in the article for SynchronizedCollection. The irony...

like image 50
Hans Passant Avatar answered Oct 12 '22 12:10

Hans Passant