Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel.ForEach - Thread Safety with Nested Instance Objects

Are the Employee and/or Illness instances thread-safe in this scenario? Does each thread have it own copy of the objects? Originally I thought that each thread would have its own copy, but now I'm not sure.

Parallel.ForEach(line01s, _options, o =>
{
    var employee = new Employee();
    // set values on employee...Safe?

    var illness = new Illness();
    // set values on illness...Safe?

    employee.AddIllness(illness);  // Illness is a property on Employee

}

Is it possible for the Illness object to be set on the wrong Employee object? Do I need to add lock around employee.AddIllness(illness);? The more I work with this TPL stuff, the more I find I don't understand

like image 883
Big Daddy Avatar asked Jun 12 '26 22:06

Big Daddy


2 Answers

Your example only works with objects creating inside the scope of the lambda expression, therefore you have nothing to worry about. If you were modifying the state of an object outside of the lambda block, then you'd need to worry about locking, etc.

like image 95
Justin Niessner Avatar answered Jun 14 '26 12:06

Justin Niessner


If you iterate Parallel.ForEach over employees collection, or create new employee inside the lambda, then there is nothing to worry. Each lambda call is completely independent of others(if there are no outer variables in closure).

If employees collection have duplicates or the processing is more complex, then you will have to use some synchronization code.

like image 33
Eugene Podskal Avatar answered Jun 14 '26 11:06

Eugene Podskal