小编And*_*nes的帖子

并行For循环在C#中使用共享变量

我正在尝试使用并行处理来加速几个嵌套循环,但我无法正确获得语法.我试图计算一个位图中有多少像素是红色,白色或黑色,我在其他地方枚举的值.

在串行处理中,我有以下代码,工作正常:

        Bitmap image = new Bitmap(@"Input.png");
        var colourCount = new int[3];

        for (var x = 0; x < image.Width; x++)
        {
            for (var y = 0; y < image.Height; y++)
            {
                switch (image.GetPixel(x, y).ToArgb())
                {
                    case (int)colours.red: colourCount[0]++; break;
                    case (int)colours.white: colourCount[1]++; break;
                    case (int)colours.black: colourCount[2]++; break;
                    default: throw new ArgumentOutOfRangeException(string.Format("Unexpected colour found: '{0}'", image.GetPixel(x, y).ToArgb()));
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

我已经看到Microsoft和来自Stackoverflow的并行for循环代码,它们更新了一个共享变量,如下所示:

        Parallel.For<int>(0, result.Count, () => 0, (i, loop, subtotal) =>
        {
            subtotal += result[i];
            return subtotal;
        },
            (x) => Interlocked.Add(ref …
Run Code Online (Sandbox Code Playgroud)

c# parallel-processing .net-4.5

6
推荐指数
1
解决办法
7023
查看次数

标签 统计

.net-4.5 ×1

c# ×1

parallel-processing ×1