I have a static List in a class that will be accessed by different threads, each one adding, reading and removing its own unique item from the list. I would like to know if I have to worry about making this variable thread safe, as even though the same List object is shared between threads, they only modify their own unique items
You definitely have to implement thread-safe access either via lock or via e.g. ReaderWriterLockSlim.
Variable itself (List<>) is thread-safe if you not modifies it after first allocation (via new) but element access have to be thread-safe (since you say you adding/removing elements from list hence changing its state)
BTW, if threads modifies its own items why you want to share them? So what you have implemented? Why you organize this way? Maybe there are better advise if you show details.
If your threads do not share the data in any way then why have them compete for access to the same list. This might be an acceptable usage of the thread local storage pattern. .NET offers the following mechanisms.
Thread.SetData
andThread.GetData
ThreadStaticAttribute
Or perhaps if you could abstract the threads into their own individual instances of a custom class and then use instance variables instead of a static list variable.
You only need to worry when you are changing the list (adding / removing). However if you are using the object which you have just got / added, then you need not worry (unless it needs to be used on multiple threads)
static List<ClientState> _clientStates;
static readonly Object _clientStatesLock = new Object();
/// Gets the state of a client for a given Id.
/// Returns null if no state exists.
/// This method is threadsafe.
ClientState GetState (ClientIdentifier id){
lock (_clientStatesLock)
return _clientStates.FirstOrDefault (cs => cs.Id == id);
}
The same goes for adding / removing items.
If you are on .NET 4, use the provided Concurrent collections whenever possible rather than implementing your own.