Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is list copy thread safe?

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?

like image 637
Alexander Pope Avatar asked Sep 30 '22 14:09

Alexander Pope


1 Answers

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.

like image 52
adv12 Avatar answered Oct 04 '22 18:10

adv12