Big Daddy
Big Daddy

Reputation: 5224

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

Upvotes: 2

Views: 1331

Answers (2)

Eugene Podskal
Eugene Podskal

Reputation: 10401

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.

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245429

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.

Upvotes: 7

Related Questions