Reputation: 1224
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?
Upvotes: 7
Views: 3852
Reputation: 465
You can lock the SyncRoot object of sharedCollection
.
Explain here : Lock vs. ToArray for thread safe foreach access of List collection
Upvotes: 0
Reputation: 8551
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.
Upvotes: 5