I need to obtain a lock in two different threads in order to access a Bitmap (which is populated from a webcam) in EmguCv. I have a "GetFrame" functions that queries the camera and places what it returns into a .NET Bitmap. I have two threads which need to access this Bitmap, one needs to write to the Bitmap and assign the Bitmap to a picture box, and the other needs to read the Bitmap, convert it to an Image object and assign that to an EMGU ImageBox. I first lock on an arbitrary Object, then I do my operations. The code is as follows (_Camera.LiveFrame is the Bitmap):
Writing/Reading Thread:
while (_CaptureThreadRunning)
{
lock (_Camera)
{
// _Camera.GetFrame writes to the Bitmap
if (_VideoPlaying && _Camera.GetFrame(500))
pbLiveFeed.Invalidate();
}
}
_Camera.CloseCamera(true);
_CaptureExitEvent.Set(); // Set to signal captureThread has finished
Reading/ImageBox Thread:
while (_ProcessThreadRunning)
{
lock (_Camera)
{
// _Camera.LiveFrame is the Bitmap
procImage = new Image<Bgr, int>((Bitmap)_Camera.LiveFrame.Clone());
procImage.Draw(new Rectangle(10,20,20,15),new Bgr(Color.LightGreen), 5);
ibProcessed.Image = procImage;
ibProcessed.Invalidate();
}
}
_ProcessExitEvent.Set();
This runs fine most of the time but every now and then I get a "Object is in use elsewhere" error when I try to Clone() the Bitmap. Is this not the proper way to lock? I don't see why this would cause a problem.
ps. My threads can no longer exit gracefully either. My .Set() calls outside of my loops are never called. I am guessing the threads are deadlocked?
Clone()throws an exception, then of courseSet()won't be called. That's how exceptions work. - svick