如何创建线程安全的通用列表? [英] How to Create a Thread-Safe Generic List?
问题描述
我有一个通用列表,如下所示:
public static readonly List< Customer> Customers =新列表< Customer>();
我使用下面的方法:
.Add
。找到
.FirstOrDefault
最后2个是LINQ扩展。
我需要使这个线程安全,才能运行容器类的多个实例。
如何达到这个目标?
如果这些是唯一的你正在使用的函数 List< T>
那么最简单的方法就是编写一个快速包装器,使访问与 lock
class MyList< T> {
私人列表< T> _list = new List< T>();
private object _sync = new object();
public void Add(T value){
lock(_sync){
_list.Add(value);
public bool Find(Predicate< T> predicate){
lock(_sync){
return _list.Find(predicate);
public T FirstOrDefault(){
lock(_sync){
return _list.FirstOrDefault();
}
}
}
我强烈建议一个新的类型+私人锁定对象。这让下一代继承你的代码的人更加明显。实际意图是什么。
另外值得注意的是.Net 4.0引入了一组新的集合,专门针对从多个线程使用。如果其中一个满足您的需求,我强烈建议使用它来滚动您自己的。-
ConcurrentStack< T>
ConcurrentQueue< T>
I have a Generic List as below
public static readonly List<Customer> Customers = new List<Customer>();
I'm using the below methods for it:
.Add
.Find
.FirstOrDefault
The last 2 are LINQ extensions.
I'd need to make this thread-safe to be able to run multiple instances of the container class.
How to achieve that?
If those are the only functions you are using on List<T>
then the easiest way is to write a quick wrapper that synchronizes access with a lock
class MyList<T> {
private List<T> _list = new List<T>();
private object _sync = new object();
public void Add(T value) {
lock (_sync) {
_list.Add(value);
}
}
public bool Find(Predicate<T> predicate) {
lock (_sync) {
return _list.Find(predicate);
}
}
public T FirstOrDefault() {
lock (_sync) {
return _list.FirstOrDefault();
}
}
}
I highly recommend the approach of a new type + private lock object. It makes it much more obvious to the next guy who inherits your code what the actual intent was.
Also note that .Net 4.0 introduced a new set of collections specifically aimed at being used from multiple threads. If one of these meets your needs I'd highly recommend using it over rolling your own.
ConcurrentStack<T>
ConcurrentQueue<T>
这篇关于如何创建线程安全的通用列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!