Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a thread safe variable when using PLINQ

I have a list of items through which I loop using PLINQ statements to increment the total earnings of a specific user like following:

 double TotalEarnings = 0.0d;
_SortedList.AsParallel().WithDegreeOfParallelism(5).ForAll(item => {
 TotalEarnings += Convert.ToDouble(item.SaleEarning);
 });

By using it like this, I always end up with a different value. I believe this is due to the fact that the declared variable is not thread safe. How can I fix this?

P.S. The _SortedList is a generic collection (List<>)...

like image 567
User987 Avatar asked Jul 26 '26 17:07

User987


1 Answers

Use Sum to get the total using PLINQ. It will take care of aggregating the sum efficiently, and safely.

double TotalEarnings = _SortedList.AsParallel()
    .WithDegreeOfParallelism(5)
    .Sum(item => item.SaleEarning);
like image 199
Servy Avatar answered Jul 28 '26 06:07

Servy



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!