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.
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.
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.
It's also important to note that List<T> is ordered and ConcurrentBag<T> is unordered.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With