.NET 列出需要的线程安全实施建议
.Net List 类不是线程安全的。我希望实现所需的最小锁定,但仍然满足要求,例如对于读取,允许幻象记录,对于写入,它们必须是线程安全的,这样就不会丢失任何更新。
所以我所做的
public static List<string> list = new List<string>();
In Methods that have **List.Add**/**List.Remove** , I always lock to assure thread safety
lock (lockHelper)
{
list.Add(obj);
or list.Remove(obj);
}
In Methods that requires **List Reading** I don't care about phantom record so I go ahead to read without any locking. In this case. Return a bool by checking whether a string had been added.
if (list.Count() != 0) {
return list.Contains("some string")
}
就是锁定写访问,并允许读访问在没有任何锁定的情况下进行。我的线程安全想法有效吗?
据我所知,列表大小有所扩展。会好吗?我的猜测是,当列表扩展时,它可能会使用临时变量。列表。这是可以的,因为临时列表大小总是有一个边界,并且 .Net 类实现得很好,即。当读取被更新时,不应该出现任何indexOutOfBound或循环引用问题。
.Net List class isn't thread safe. I hope to achieve the minimal lock needed and yet still fulfilling the requirement such that as for reading, phantom record is allowed, and for writing, they must be thread-safe so there won't be any lost updates.
So I have something like
public static List<string> list = new List<string>();
In Methods that have **List.Add**/**List.Remove** , I always lock to assure thread safety
lock (lockHelper)
{
list.Add(obj);
or list.Remove(obj);
}
In Methods that requires **List Reading** I don't care about phantom record so I go ahead to read without any locking. In this case. Return a bool by checking whether a string had been added.
if (list.Count() != 0) {
return list.Contains("some string")
}
All I did was locking write accesses, and allow read accesses to go through without any locking. Is my thread safety idea valid?
I understand there is List size expansion. Will it be ok? My guess is that when a List is expanding, it may uses a temp. list. This is ok becasue the temp list size will always have a boundary, and .Net class is well implemented, ie. there shouldn't be any indexOutOfBound or circular reference problems when reading was caught in updates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,那不安全。您应该防止读取和枚举。
由于您使用的是 4.0,请查看新的线程安全集合。
http://msdn.microsoft.com/en-us/library/dd997305.aspx
No that is not safe. You should protect against reads and enumerations.
Since you are using 4.0, check out the new thread safe collections.
http://msdn.microsoft.com/en-us/library/dd997305.aspx
如果您使用的是.NET Framework 4;为什么不使用
ConcurrentBag
?If you are using .NET Framework 4; Why not use
ConcurrentBag<T>
?由于您使用的是 .NET 4.0,因此您应该只使用 ConcurrentBag,因为它提供了 UnorderedList 的线程安全实现。
您可以在此处查看所有线程安全集合
.NET 线程安全集合
Since you are using .NET 4.0 you should just use the
ConcurrentBag<T>
as it provides as threadsafe implementation of an UnorderedList.You can see all the Thread-Safe Collections here
.NET Thread Safe Collections