Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T> doesn't implements SyncRoot!

Everyone use lot of List. I need to iterate over this list, so I use the known SyncRoot pattern.

Recently I noticed in this post that the SyncRoot should be avoided in favor of "embedded" thread-safety (each method will lock on an private object without exposing it using SyncRoot property). I can understand it, and partially I agree on that.

The question is that List<T> class doesn't implements the SyncRoot property, even if implements the ICollection interface, which expose the SyncRoot property. I say this bause the code

 List<int> list = new List<int>()
 list.SyncRoot;

give me the following compiler error:

error CS0117: 'System.Collections.Generic.List' does not contain a definition for 'SyncRoot'

...If this is true, how could I synchronize a public property of type List<T> when iterating over it?

like image 543
Luca Avatar asked Nov 01 '10 07:11

Luca


1 Answers

It is actually implemented explicitly.

object ICollection.SyncRoot
{
    get
    {
        if (this._syncRoot == null)
        {
            Interlocked.CompareExchange(ref this._syncRoot, new object(), null);
        }
        return this._syncRoot;
    }
}

This means you must cast to ICollection to use it.

like image 71
ChaosPandion Avatar answered Sep 21 '22 07:09

ChaosPandion