As far as Thread Safety goes is this ok to do or do I need to be using a different collection ?
List<FileMemberEntity> fileInfo = getList(); Parallel.ForEach(fileInfo, fileMember => { //Modify each fileMember }
As long as you are only modifying the contents of the item that is passed to the method, there is no locking needed.
(Provided of course that there are no duplicate reference in the list, i.e. two references to the same FileMemberEntity
instance.)
If you need to modify the list itself, create a copy that you can iterate, and use a lock when you modify the list:
List<FileMemberEntity> fileInfo = getList(); List<FileMemberEntity> copy = new List<FileMemberEntity>(fileInfo); object sync = new Object(); Parallel.ForEach(copy, fileMember => { // do something lock (sync) { // here you can add or remove items from the fileInfo list } // do something });
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