问题描述
每个人都使用很多列表.我需要遍历这个列表,所以我使用已知的 SyncRoot 模式.
Everyone use lot of List. I need to iterate over this list, so I use the known SyncRoot pattern.
最近我在 这篇 帖子中注意到 SyncRoot 应该是避免支持嵌入式"线程安全(每个方法都将锁定一个私有对象,而不使用 SyncRoot 属性公开它).我可以理解,并且部分同意.
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.
问题是 List<T> 类没有t 实现 SyncRoot 属性,即使实现 ICollection 接口,它公开了 SyncRoot 属性.我说这是因为代码
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;
给我以下编译器错误:
错误 CS0117:System.Collections.Generic.List"不包含SyncRoot"的定义
error CS0117: 'System.Collections.Generic.List' does not contain a definition for 'SyncRoot'
...如果这是真的,我如何同步 List<T> 类型的公共属性?什么时候迭代它?
...If this is true, how could I synchronize a public property of type List<T> when iterating over it?
推荐答案
其实是显式实现的.
object ICollection.SyncRoot
{
get
{
if (this._syncRoot == null)
{
Interlocked.CompareExchange(ref this._syncRoot, new object(), null);
}
return this._syncRoot;
}
}
这意味着您必须强制转换为 ICollection
才能使用它.
This means you must cast to ICollection
to use it.
这篇关于列出<T>没有实现 SyncRoot!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!