Object is currently in use somewhere else error when using Paraller.For

271 views Asked by At

I am trying to parallelize an operation on an image using the code below , but I get an One or more errors occurred error.

Looking into the inner exception I can see the error {"Object is currently in use elsewhere."} has occurred.

Note: CoverImage and SecretImage are Bitmaps

 Parallel.For(0, CoverImage.Width, x =>
            {
                for (int y = 0; y < CoverImage.Height; y++, SecretImageHeight++)
                {
                    Color coverImagesPixel = CoverImage.GetPixel(x, y);
                    Color secretImagesPixel = SecretImage.GetPixel(SecretImageWidth, SecretImageHeight);

                    int r = (coverImagesPixel.R & coverImageMask) + ((secretImagesPixel.R >> shift) & secretImageMask);
                    int g = (coverImagesPixel.G & coverImageMask) + ((secretImagesPixel.G >> shift) & secretImageMask);
                    int b = (coverImagesPixel.B & coverImageMask) + ((secretImagesPixel.B >> shift) & secretImageMask);

                    StegoImage.SetPixel(x, y, Color.FromArgb(255, r, g, b));
                }
                SecretImageHeight = 0;
                SecretImageWidth++;
            }
            );

I tried using a mutex like this :

mutex.WaitOne();
StegoImage.SetPixel(x, y, Color.FromArgb(255, r, g, b));
mutex.ReleaseMutex();

But still to no avail (I get the same error).

1

There are 1 answers

2
Jon Skeet On BEST ANSWER

It looks like you're trying to use image APIs from non-UI threads. That's a bad idea.

I suggest you copy the image to a byte array on the UI thread, then run your parallel for loop which would mutate the array, then recreate the image afterwards from the byte array.