开发者

List<T> doesn't implements SyncRoot!

开发者 https://www.devze.com 2023-01-23 11:28 出处:网络
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-sa

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 pr开发者_如何学编程operty. 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消