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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With