WPF - 更新“System.Windows.Controls.Image”来自另一个线程
我在该代码上遇到了这个异常。 如何修复它?
例外:
调用线程无法访问此 对象,因为不同的线程拥有 它。
代码:
void CamProc_NewTargetPosition(IntPoint Center, System.Drawing.Bitmap image)
{
IntPtr hBitMap = image.GetHbitmap();
BitmapSource bmaps = Imaging.CreateBitmapSourceFromHBitmap(hBitMap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
Dispatcher.BeginInvoke((Action)(() =>
{
labelX.Content = String.Format("X: {0}", Center.X); //OK Working
labelY.Content = String.Format("Y: {0}", Center.Y); //OK Working
pictureBoxMain.Source = bmaps; // THERE IS EXCEPTON
}), DispatcherPriority.Render, null);
}
pictureBoxMain是System.Windows.Controls.Image。
I get this exception on that code.
How to fix it?
Excepton:
The calling thread cannot access this
object because a different thread owns
it.
Code:
void CamProc_NewTargetPosition(IntPoint Center, System.Drawing.Bitmap image)
{
IntPtr hBitMap = image.GetHbitmap();
BitmapSource bmaps = Imaging.CreateBitmapSourceFromHBitmap(hBitMap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
Dispatcher.BeginInvoke((Action)(() =>
{
labelX.Content = String.Format("X: {0}", Center.X); //OK Working
labelY.Content = String.Format("Y: {0}", Center.Y); //OK Working
pictureBoxMain.Source = bmaps; // THERE IS EXCEPTON
}), DispatcherPriority.Render, null);
}
pictureBoxMain is System.Windows.Controls.Image.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以冻结 BitmapSource,以便可以从任何线程访问它:
You can freeze the BitmapSource so that it can be accessed from any thread:
您可以按照另一个线程中的建议冻结图像,这可以摆脱线程限制,但使图像不可变。
WPF/BackgroundWorker 和 BitmapSource 问题
You could Freeze the image, as suggested in another thread, which gets rid of the threading restriction but makes the image immutable.
WPF/BackgroundWorker and BitmapSource problem