john
john

Reputation: 31

List shared between different threads in .NET

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

Upvotes: 3

Views: 8377

Answers (4)

Ian Mercer
Ian Mercer

Reputation: 39277

If you are on .NET 4, use the provided Concurrent collections whenever possible rather than implementing your own.

See http://msdn.microsoft.com/en-us/library/dd997305.aspx

Upvotes: 2

user164771
user164771

Reputation:

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.

Upvotes: 2

Brian Gideon
Brian Gideon

Reputation: 48949

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 and Thread.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.

Upvotes: 2

Nick Martyshchenko
Nick Martyshchenko

Reputation: 4249

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.

Upvotes: 10

Related Questions