I'm trying to use parallel processing to speed up a couple of nested loops, but it's hard for me to get the syntax correctly. I am trying to calculate how many pixels in a bitmap will be red, white or black, the values ββthat I have in an enumeration elsewhere.
In sequential processing, I have the following code that works fine:
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())); } } }
I saw code for parallel loops of Microsoft and Stackoverflow that update a shared variable, like below:
Parallel.For<int>(0, result.Count, () => 0, (i, loop, subtotal) => { subtotal += result[i]; return subtotal; }, (x) => Interlocked.Add(ref sum, x) );
But all the examples use a simple type such as int as a shared variable, and I just can't figure out the syntax for writing to my array of size three. Am I approaching this all wrong?
By the way, I know in terms of performance that GetPixel is very slow compared to something like Bitmap.LockBits, I'm just trying to get the principle of parallel loops.
source share