HOPE
HOPE

Reputation: 152

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. 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? How List object is implemented?

Upvotes: 2

Views: 1017

Answers (2)

weichch
weichch

Reputation: 10035

List is not thread safe.

The problem you're solving looks like a producer-consumer problem, so what you need is a collection which implements IProducerConsumerCollection<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.

Upvotes: 3

vasily.sib
vasily.sib

Reputation: 4002

As from the docs:

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.

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.

Like ConcurrentQueue, for example. 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.

Upvotes: 5

Related Questions