6

Is it safe to use the following pattern in a multithreaded scenario?:

var collection = new List<T>(sharedCollection);

Where sharedCollection can be modified at the same time by another thread (i.e. have elements added or removed from it)?

The scenario I'm currently dealing with is copying the items from a BindingList, but the question should be relative to any standard collection type.

If it isn't thread safe, should I put a lock on the sharedCollection, or are there better solutions?

Cloud
  • 938
  • 1
  • 8
  • 24
Alexander Pope
  • 1,134
  • 1
  • 12
  • 22

2 Answers2

5

You seem to have answered your own question(s). No, copying a changing list to another list is not thread-safe, and yes, you could lock on sharedCollection. Note that it's not enough to lock sharedCollection while copying it; you need to lock it anytime you read or change its contents as well.

Edit: just a note about when it's bad to lock on the object you're modifying--if the object reference itself can be changed (like `sharedCollection = new List) or if it can be null, then make a separate object to lock on as a member of the class where the reading/writing is happening.

adv12
  • 8,443
  • 2
  • 24
  • 48
  • 1
    I hoped the collection copy was thread safe, so no lock would be required. In this case, I will create the list copy on the GUI thread to avoid the lock. – Alexander Pope Jun 11 '14 at 20:53
  • 1
    @AlexanderPope, Can `sharedCollection` be modified from a background thread while you are copying it on the GUI thread? If so, you're still not threadsafe. You either have to make sure the list is only being used by one thread or go all the way with locking... – adv12 Jun 11 '14 at 20:56
  • 1
    Nope, the use case is to remove items from the binding based on some criteria, and to do so, I needed a copy of the binding list to iterate. I didn't like the idea of making the copy on the gui thread, but that seems the cleanest way. I am aware that locking on the collection can lead to deadlocks, but I wanted to make the question as basic as it can be. – Alexander Pope Jun 11 '14 at 21:02
0

You can lock the SyncRoot object of sharedCollection.

Explain here : Lock vs. ToArray for thread safe foreach access of List collection

Community
  • 1
  • 1
fred
  • 465
  • 2
  • 7