问题描述
我要的实施列表< T>
作为可以线程安全地使用没有任何怀疑的属性。
I want an implementation of List<T>
as a property which can be used thread-safely without any doubt.
事情是这样的:
private List<T> _list;
private List<T> MyT
{
get { // return a copy of _list; }
set { _list = value; }
}
看来我还是需要返回集合的副本(克隆),所以如果某个地方,我们遍历集合和集合设置在同一时间,则不会引发异常。
It seems still I need to return a copy (cloned) of collection so if somewhere we are iterating the collection and at the same time the collection is set, then no exception is raised.
如何实现一个线程安全的集合属性?
How to implement a thread-safe collection property?
推荐答案
如果您正在打靶的.Net 4中有System.Collections.Concurrent命名空间
If you are targetting .Net 4 there are a few options in System.Collections.Concurrent Namespace
您可以使用 ConcurrentBag&LT; T&GT;
在这种情况下,而不是列表&LT; T&GT;
You could use ConcurrentBag<T>
in this case instead of List<T>
这篇关于线程安全的List&LT; T&GT;属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!