Consider my following (simplified) code:
public double ComputeSum(List<double> numbers, ref double threshold, Object thresholdLock)
{
double sum = 0;
Object sumLock = new Object();
Parallel.ForEach (numbers, (number) =>
{
bool numberIsGreaterOrEqualThanThreshold;
lock (thresholdLock)
{
numberIsGreaterOrEqualThanThreshold = number >= threshold;
}
if (numberIsGreaterOrEqualThanThreshold)
{
lock (sumLock)
{
sum += number;
}
}
});
return sum;
}
This code does not compile. The compiler error message is:
Cannot use ref or out parameter 'threshold' inside an anonymous method, lambda expression, or query expression
The goal of this parallel ComputeSum method is to parallely compute the sum of some numbers of the 'numbers' parameter list. This sum will include all the numbers that are greater or equal to the referenced threshold ref parameter.
This threshold parameter is passed as a ref because it can be modified by some other tasks during the ComputeSum method execution, and I need each number comparaison to be made with the current threshold value at the time at which the comparaison with the threshold is made. (I know, in this simplified example it may appear silly to do this but the actual code is more complex and makes sense).
My question is: What workaround can I use to access the threshold by ref inside the Parallel.ForEach lambda-expression statement ?
Note: I read the "said duplicate" question Cannot use ref or out parameter in lambda expressions but I'm not asking why this ref parameter access is refused by the compiler but I'm asking for a workaround to do what I intend to do.