I know Bitmaps are not threadsafe, and hence using this workaround
Bitmap[] blobCopies = MakeBlobCopies(bmpBlob, 2);
BackgroundWorker bw1 = new BackgroundWorker();
bw1.DoWork += new DoWorkEventHandler(bw1_DoWork);
bw1.RunWorkerAsync(blobCopies[0]);
BackgroundWorker bw2 = new BackgroundWorker();
bw2.DoWork += new DoWorkEventHandler(bw2_DoWork);
bw2.RunWorkerAsync(blobCopies[1]);
DisposeBlobCopies(blobCopies);
In the Backgroundwork event handle , I apply some filters to the bitmaps but I get the an Access Violation Exception
System.AccessViolationException was unhandled
Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Source=System.Drawing
StackTrace:
at System.Drawing.SafeNativeMethods.Gdip.GdipBitmapLockBits(HandleRef bitmap, GPRECT& rect, ImageLockMode flags, PixelFormat format, BitmapData lockedBitmapData)
at System.Drawing.Bitmap.LockBits(Rectangle rect, ImageLockMode flags, PixelFormat format, BitmapData bitmapData)
at System.Drawing.Bitmap.LockBits(Rectangle rect, ImageLockMode flags, PixelFormat format)
I am not even disposing the bitmaps (which I would need to avoid choking up memory). BUt still get this exception. I do not need to return anything from the worker thread, the
Is this the right away to even approach this? Any ideas?
private Bitmap[] MakeBlobCopies(Bitmap originalBitmap, int n)
{
Bitmap[] blobCopies = new Bitmap[n];
for (int i = 0; i < n; i++)
{
blobCopies[i] = (Bitmap)originalBitmap.Clone();
}
return blobCopies;
}
No, bitmaps are thread-safe. They are protected by an internal lock, you’ll get an exception when you try to read a bitmap when it is being written to by another thread.
Disposing the bitmaps while the threads are using them is however hazardous, that jerks the floor mat. Especially when you use Bitmap.Clone(), it doesn’t make a copy of the pixel data. Only the Bitmap(Image) constructor does that. You’ll need to find a better place for the Bitmap.Dispose() call. Like in the DoWork or RunWorkerCompleted event handler, after you are sure that the bitmap isn’t going to be accessed anymore.