Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel.ForEach on List<Object> Thread Safety

Tags:

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          } 
like image 398
Micah Armantrout Avatar asked Jun 27 '12 17:06

Micah Armantrout


1 Answers

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 }); 
like image 134
Guffa Avatar answered Sep 18 '22 16:09

Guffa