for (int x = 0; x < blockCountX; x++)
{
for (int y = 0; y < blockCountY; y++)
{
//get blocks from image to new image and send to threaded processor
imageBlocks[x, y] = image.Clone(clipRectangle, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ThreadedFromHeightMap));
t.Start(imageBlocks[x,y]);
clipRectangle.Offset(0, IMAGEBLOCKSIZE);
}
clipRectangle.Offset(IMAGEBLOCKSIZE, clipRectangle.Location.Y * -1);
}
break;
}
}
private void ThreadedFromHeightMap(object Image)
{
Bitmap image = (Bitmap)Image;
int width = image.Width;
int height = image.Height;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
map.Hexes.Add(new Point(x, y), new Hex(image.GetPixel(x, y).B));
//tempHexes.Enqueue(new Hex(image.GetPixel(x, y).B));
}
}
}
I'm trying to take pixel data from a 2048 x 2048 8bpp grayscale heightmap and building a hex map with corresponding height values. I'm storing the hexes in a Dictionary collection. All told there's ~4 million hexes in the collection.
To do this efficiently I'm breaking the image up into 256 x 256 chunks and passing that image to another thread which will parse it and add the hexes to the collection. This is were it all goes haywire. Instead of one image with (0,0) as its top left corner, I now have 64 image chunks that have (0,0) as their top left corner. However I'm using the pixel location as an index for the dictionary. This crashes when the second thread tries to add another value with index (0,0).
How do I mitigate this problem? I've thought about building a class that just has an image member and a chunk number member and pass that to the thread so I can adjust the pixel location depending on what chunk the thread is working on but that seems less than optimal.
(I realize the Dictionary I'm using isn't thread safe. I've since fixed that.)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…