我以大约30次/秒的速度从相机获取图像,并且在转换图像期间,我想防止相机释放源图像。
在此代码中,bmp
是源writeablebitmap
图像(相机获取的图像)和目标图像(转换后的图像和显示的图像)
为此,我用了 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);
}
}));
});
这种方法似乎可行,但是它的性能确实很差(因为新的30次/秒)。我在https://msdn.microsoft.com/en-us/library/c5kehkcz.aspx上看到可以使用的相同实例tempLock
。
所以我的代码部分变成:
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);
}
}));
});
问题在于writeableBitmap始终为黑色。
为什么我做得不好?
谢谢
编辑:我找到了一个解决方案,我把Object tempLock = new Object();
外部构造函数(直接在类中,它的工作,但我不知道为什么)
当您将Object tempLock = new Object();
构造函数放在外部时,您只需要在主线程中初始化一次即可。但是,当您将其放入其中时,您将ImageTarget.Dispatcher.BeginInvoke()
在后台线程上对其进行初始化。因此,tempLock的值在主线程上保持为空,并且不可能锁定为空值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句