基于这个 example 我试图用元组返回做一个并行的 foreach。

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");

上面的代码工作正常,但在我的情况下(正确的最小值)但我不想输出最小值而是该值的“名称”,所以我尝试了这样的事情:
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");

尝试了一些不起作用的东西。我也没有运气读过microsoft's example
任何帮助表示赞赏。

最佳答案

你的问题没有太多的背景。最好提供一个很好的 Minimal, Complete, and Verifiable code example 来准确显示你在做什么。但是,似乎在您的第二个版本的代码中,您已将计算模型从具有 PerformComputation() 方法的对象更改为本地定义的 PerformComputation() 方法,以及某种 Tuple 对象的集合,其中 Item1成员是某种 KeyValuePair<TKey, TValue>

做出这些假设,这样的事情应该适用于您的场景:

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;
            }
        }
    }
);

关于c# - Parallel.ForEach 与元组返回 c#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45258311/

10-10 23:11