Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T> concurrent removing and adding

I am not too sure, so i thought i'd ask. Would removing and adding items to a System.Collections.Generic.List<> object be non-thread safe?

My situation:

When a connection is received, it is added to the list, but also at the same time, there's a worker that's removing dead connections and such.

Is there a problem? Will a lock do? I also want to know if i'm allowed to use a lock on the list object with it's Foreach<> method.

like image 565
TheAJ Avatar asked Nov 28 '09 19:11

TheAJ


People also ask

Is list AddRange thread-safe?

No it is not thread-safe. Thread A could call AddRange on your list. It could iterate partially over the collection and switch threads. Thread B could call Add/Remove, etc.

Which is thread-safe when list is modified?

To put it simply, a class instance is immutable when its internal state can't be modified after it has been constructed. A MessageService object is effectively immutable since its state can't change after its construction. So, it's thread-safe.

Is ConcurrentBag ordered?

It's also important to note that List<T> is ordered and ConcurrentBag<T> is unordered.

What is concurrent collection in C#?

Concurrent namespace. This has several collection classes that are thread-safe and scalable. These collections are called concurrent collections because they can be accessed by multiple threads at a time.


1 Answers

Yes, adding and removing items from a List<> is not thread safe, so you need to synchronise the access, for example using lock.

Mind that the lock keyword in no ways locks the object that you use as identifier, it only prevents two threads to enter the same code block at the same time. You will need locks around all code that accesses the list, using the same object as identifier.

like image 52
Guffa Avatar answered Oct 12 '22 01:10

Guffa