Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread Safety for Parallel Tasks in .NET

Are the internals of a delegate to the Task Parallel Library thread safe - i.e. is that value of a variable declared within that delegate isolated to that thread?

Example:

Parallel.ForEach(collection, item => {
    var something = new Something(item.Property);
});

Is something guaranteed to always be a unique to a thread, protected against being overwritten by another thread created by the same Parallel operation?

like image 636
lukiffer Avatar asked Dec 01 '25 22:12

lukiffer


1 Answers

Since this is a delegate something is a local variable and certainly thread-safe if it is of a value type - of course it can still be overwritten if the variable holds a reference to a shared reference object (e.g. a reference to a variable that the delegate uses as a closure)

like image 88
BrokenGlass Avatar answered Dec 03 '25 14:12

BrokenGlass



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!