Reputation: 7253
I acquire an image from a camera about 30 times / second, and, during I'm converting this image, I would like to prevent the camera to free the source image.
In this code, bmp
is the source (the image acquired by the camera) and writeablebitmap
the destination image (after the conversion and the image displayed)
For that, I used lock
Messenger.Default.Register<Bitmap>(this, (bmp) =>
{
ImageTarget.Dispatcher.BeginInvoke((Action)(() =>
{
if (ImageTarget.Source == null && bmp != null)
{
ImageTarget.Source = writeableBitmap;
}
Object tempLock = new Object();
lock (tempLock)
{
Util.ImageConverter.Convert(bmp, writeableBitmap);
}
}));
});
this method seems working, but, it's really have bad performance (cause the new 30times/second). I see on https://msdn.microsoft.com/en-us/library/c5kehkcz.aspx that I could use the same instance of tempLock
.
So my code part becomes :
Object tempLock = new Object();
Messenger.Default.Register<Bitmap>(this, (bmp) =>
{
ImageTarget.Dispatcher.BeginInvoke((Action)(() =>
{
if (ImageTarget.Source == null && bmp != null)
{
ImageTarget.Source = writeableBitmap;
}
lock (tempLock)
{
Util.ImageConverter.Convert(bmp, writeableBitmap);
}
}));
});
The problem is that the writeableBitmap is always black.
Why I'm doing bad ?
Thanks
Edit: I found a solution, I put the Object tempLock = new Object();
outside the constructor (directly in the class and it's work, but I don't know why)
Upvotes: 0
Views: 106
Reputation: 2130
When you put the Object tempLock = new Object();
outside the constructor, you are initializing it only once in the main thread. However when you put it inside the ImageTarget.Dispatcher.BeginInvoke()
you are initializing it on a background thread. So the value of tempLock remains null on the main thread and it is not possible to lock on a null value.
Upvotes: 1