C#并行返回值

时间:2016-05-21 05:22:01

标签: c# parallel-processing aggregation

我使用以下代码尝试使用来自两个单独数组的值进行一些计算。我一直在尝试聚合值列表作为最后一步,但每次运行程序时,它只在列表中有一组值。 abcXLoopVars是一个自定义类,用于存储我稍后聚合的不同变量。

Parallel.For<abcXLoopVars>(0, colX.Count(),
            () => { return new abcXLoopVars(); },
            (i, pls, state) =>
        {
            state = new abcXLoopVars();
            double x = Math.Abs(colX[i]);
            double y =   Math.Abs(colY[i]);
            double lnx = Math.Log(x);
            double lny = Math.Log(y);
            double xminxbarsq = Math.Pow(colX[i] - xbar, 2);
            double xminxbarcub = Math.Pow(colX[i] - xbar, 4);
            state.sumxminxbarsq = xminxbarsq;
            state.sumxminxbarcub = xminxbarcub;
            state.sumlnxxminxbarsq = lnx * xminxbarsq;
            state.sumlnxlny = lnx * lny;
            state.sumlnxsq = Math.Pow(lnx, 2);
            state.sumlnx = sumlnx + lnx;
            state.sumlnyxminxbarsq = lny * xminxbarsq;
            state.sumlny = lny;
            state.posneg = colY[i] / colX[i];

            return state;
        },
        (state) => { lock (lockMe) abxList.Add(state);}
        );

1 个答案:

答案 0 :(得分:0)

我建议你把它重写为PLINQ:

    colX.Zip(colY, (x, y) =>
        {
            var state = new abcXLoopVars();
            double lnx = Math.Log(x);
            double lny = Math.Log(y);
            double xminxbarsq = Math.Pow(x - xbar, 2);
            double xminxbarcub = Math.Pow(x - xbar, 4);
            state.sumxminxbarsq = xminxbarsq;
            state.sumxminxbarcub = xminxbarcub;
            state.sumlnxxminxbarsq = lnx * xminxbarsq;
            state.sumlnxlny = lnx * lny;
            state.sumlnxsq = Math.Pow(lnx, 2);
            state.sumlnx = sumlnx + lnx;
            state.sumlnyxminxbarsq = lny * xminxbarsq;
            state.sumlny = lny;
            state.posneg = y / x;

            return state;
        }).AsParallel().ToList();