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<>)...
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With