List doesn't implements SyncRoot!

2019-02-08 15:43发布

问题:

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?

回答1:

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.