Parallel.ForEach with returning a tuple c #

Based on this example , I am trying to make a parallel foreach returning a tuple.

double min = double.MaxValue;

object syncObject = new object(); 
Parallel.ForEach(collection, () => double.MaxValue, (item, loopState, 
    localState) =>
    {
        double value = item.PerformComputation();
        return System.Math.Min(localState, value);
    },
    localState =>
    {
        lock(syncObj)
            min = System.Math.Min(min, localState);
    }
);

Console.Write(min + "\n");

      

The above code works fine, but in my case (correct minimum value), but I don't want to output the minimum value, but the "name" of that value, so I tried something like this:

double min = double.MaxValue;
string minName = "";

object syncObject = new object(); 
Parallel.ForEach(collection, () => Tuple.Create(double.MaxValue, ""), (item, 
    loopState, localState) =>
    {
        double value = PerformComputation(item.Item1.Value);
        string name = item.Item1.Key;

        return //helpHere
    },
    localState =>
    {
        lock(syncObj)
            min = //help here
            minName = //help here
    }
);

Console.Write(minName + "\n");

      

Tried a couple of things that didn't work. Also, I read the microsoft example with no luck. Any help is appreciated.

+3


source to share


2 answers


There is not much context in your question. It would be better if you provide a nice minimal, complete and tested example of code that shows you exactly what you are doing. But it looks like in your second version of the code, you changed the computational model from an object with a method PerformComputation()

, to a local method definition PerformComputation()

and a collection of some type Tuple

, where the element Item1

is KeyValuePair<TKey, TValue>

some kind.

Keeping these assumptions in mind, something like this should work in your scenario:



Tuple<double, string> result = Tuple.Create(double.MaxValue, "");

object syncObject = new object(); 
Parallel.ForEach(collection, () => Tuple.Create(double.MaxValue, ""),
    (item, loopState, localState) =>
    {
        double value = PerformComputation(item.Item1.Value);

        if (value < localState.Item1)
        {
            localState = Tuple.Create(value, item.Item1.Key);
        }

        return localState;
    },

    localState =>
    {
        lock(syncObj)
        {
            if (localState.Item1 < result.Item1)
            {
                result = localState;
            }
        }
    }
);

      

+4


source


I'm not entirely sure I understand this example, but it should be easier with PLINQ:



string minName = collection.AsParallel()
     .Min(item => Tuple.Create(PerformComputation(item.Item1.Value), item.Item1.Key)).Item2;

      

+2


source







All Articles