Listlt;Tgt; doesn#39;t implements SyncRoot!(列出lt;Tgt;没有实现 SyncRoot!)
问题描述
每个人都使用很多列表.我需要遍历这个列表,所以我使用已知的 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!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:列出<T>没有实现 SyncRoot!


- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01