List <t>不实现SyncRoot!</t>

时间:2010-11-01 07:55:35

标签: c# collections synchronization

每个人都使用很多List。我需要遍历此列表,因此我使用已知的SyncRoot模式。

最近我在this帖子中注意到应该避免使用SyncRoot以支持“嵌入式”线程安全(每个方法将锁定私有对象而不使用SyncRoot属性暴露它)。我能理解,部分我同意。

问题是List<T>类没有实现SyncRoot属性,即使实现了ICollection接口,它暴露了 SyncRoot 属性。我说这是代码

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

给我以下编译错误:

  

错误CS0117:'System.Collections.Generic.List'不包含'SyncRoot'的定义

...如果是这样,我怎么能同步List&lt; T&gt;类型的公共属性?迭代它时?

1 个答案:

答案 0 :(得分:18)

实际上是明确实施的。

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

这意味着您必须转发ICollection才能使用它。