Is it safe to add and remove items from a List object?

Viewed 347

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?

2 Answers

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.

Related