[英]Is it safe to add and remove items from a List object?
Assume we have multiple threads and a public List
that is responsible to hold real-time data.假设我们有多个线程和一个负责保存实时数据的公共
List
。 We have some thread that is responsible to add data to list object.我们有一些线程负责将数据添加到列表对象。 Another thread is responsible to get data from list object and then remove the items from top.
另一个线程负责从列表对象中获取数据,然后从顶部删除项目。
Question: Is it safe to remove from begin of a List
and simultaneously add data to end of list in separate threads?问题:从
List
开头删除并同时在单独的线程中将数据添加到列表的末尾是否安全? How List
object is implemented? List
对象是如何实现的?
Public static members of this type are thread safe.
这种类型的公共静态成员是线程安全的。 Any instance members are not guaranteed to be thread safe.
不保证任何实例成员都是线程安全的。
It is safe to perform multiple read operations on a List, but issues can occur if the collection is modified while it's being read.
对 List 执行多次读取操作是安全的,但如果在读取时修改集合,则可能会出现问题。
So, if your collection can be modified by some of the threads - you need to lock it on write and read operations.因此,如果您的集合可以被某些线程修改 - 您需要在写入和读取操作上锁定它。
The docs also points you to another solution:文档还为您提供了另一种解决方案:
For collections with built-in synchronization, see the classes in the System.Collections.Concurrent namespace.
有关具有内置同步的集合,请参阅System.Collections.Concurrent命名空间中的类。
Like ConcurrentQueue , for example.例如,像ConcurrentQueue 。 Use
.Enqueue(obj)
to insert it at the end of the queue and TryDequeue(out obj)
to get it from the top of the queue.使用
.Enqueue(obj)
将其插入到队列的末尾,并使用TryDequeue(out obj)
从队列的顶部获取它。
List is not thread safe. List 不是线程安全的。
The problem you're solving looks like a producer-consumer problem, so what you need is a collection which implements IProducerConsumerCollection<T>
:您正在解决的问题看起来像是生产者-消费者问题,因此您需要的是一个实现
IProducerConsumerCollection<T>
的集合:
System.Collections.Concurrent.ConcurrentBag<T>
System.Collections.Concurrent.ConcurrentQueue<T>
System.Collections.Concurrent.ConcurrentStack<T>
If you also need bounded buffer (only allow certain amount of items in the collection at all time), you could use BlockingCollection<T>
, with any of the above as inner collection.如果您还需要有界缓冲区(始终只允许集合中有一定数量的项目),您可以使用
BlockingCollection<T>
,将上述任何一个作为内部集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.