want to: sum x and sum x*x. Where x = line[i]. Because more than one thread wants to read/write to the \"sumAll\" and \"sumAllQ\" I need to lock its access. The problem is that
As suggested in the comments, you can use Aggregate
to accomplish this with AsParallel
in LINQ. For example:
using System.Linq;
//A class to hold the results.
//This can be improved by making it immutable and using a constructor.
public class Result
{
public double SumAll { get; set; }
public double SumAllQ { get; set; }
}
And you can use LINQ like so:
var result = line.AsParallel().Aggregate(new Result(), (input, value) => new Result {SumAll = input.SumAll+value, SumAllQ = input.SumAllQ+value*value});
Or even better:
var pline = line.AsParallel().WithDegreeOfParallelism(Environment.ProcessorCount);
var result = new Result { SumAll = pline.Sum(), SumAllQ = pline.Sum(x => x * x) };
AsParallel
doesn't give you the ability to directly specify options, but you can use .WithDegreeOfParallelism()
, .WithExecutionMode()
, or .WithMergeOptions()
to give you more control. You may have to use WithDegreeOfParallelism
to even get it to run with multiple threads.