I'm working in an API that calls the main function through multiple threads. I'm trying to access through that function a Bitmap in another class and write from it, but even after setting it to use completely different instance of the object I am experiencing an InvalidOperationException: Bitmap region is already locked.
I've tried locking code in the main function and where Bitmap.LockBits(...) is being called. Yes, UnlockBits is being called when I'm done.
/* Part of Class B */
public Surface imageSurface //Surface is a field of pixels, more or less.
{
get
{
if (_CurrImage != null && _imageSurface == null)
{
_imageSurface = Surface.CopyFromBitmap(_CurrImage);
return Surface.CopyFromBitmap(_imageSurface.CreateAliasedBitmap());
}
else
{
Surface clearPixel = new Surface(1, 1);
clearPixel[0, 0] = ColorBgra.FromBgra(255, 255, 255, 0);
return clearPixel;
}
}
}
/* the "main" function, Class A */
public override void Render(ClassBPrototype parameters, ...)
{
ClassB token = (ClassB)parameters; // Here we go again~!
...
Surface ourSurface = dstArgs.Surface;
if (token.imageSurface.Size != null)
{
ourSurface = token.imageSurface;
}
lock(typeof(ClassA))
{
for (int lRectangleIndex = ...)
{
Rectangle lRectangle = rois[lRectangleIndex];
for (int y = ...)
{
surfaceY = (ourSurface.Height / 2) - (y - (int)CenterY);
for (int x = ...)
{
surfaceX = (ourSurface.Width / 2) - (x - (int)CenterX);
if (surfaceX >= 0 && surfaceX < ourSurface.Width && surfaceY >= 0 && surfaceY < ourSurface.Height)
{
dstArgs.Surface[x, y] = ourSurface[surfaceX, surfaceY];
}
else
{
dstArgs.Surface[x, y] = ColorBgra.FromBgra(255, 255, 255, 0);
}
}
}
}
}
}