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?
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:
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: