TheWommies
TheWommies

Reputation: 5072

lock iList .net thread safe

Im just confused why adding to a list would not be thread safe like below

object aLock = new object();
List<string> aList = new List<string>

lock(aLock)
   aList.Add("abc");

Not sure why a lock would be required where all you are doing is adding to it. Why would such a scenario be not thread safe?

Upvotes: 1

Views: 345

Answers (1)

Chris Shain
Chris Shain

Reputation: 51329

The example code is useless- as @Jon mentions, all threads would be locking on their own object, which means they wouldn't be blocking each other at all. Might as well leave out the lock statement entirely.

First of all, you need to lock on an object that's common to all of the threads (like the list itself). For instance:

lock (aList)
    aList.Add("abc");

As for "why", the internal implementation of the List may (does) perform actions that are not safe to perform in parallel on multiple threads. This is documented in the List class MSDN docs:

Public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

A List can support multiple readers concurrently, as long as the collection is not modified. Enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with one or more write accesses, the only way to ensure thread safety is to lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

Upvotes: 2

Related Questions