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开发者_JS百科.Content = String.Format("Y: {0}", Center.Y); //OK Working
pictureBoxMain.Source = bmaps; // THERE IS EXCEPTON
}), DispatcherPriority.Render, null);
}
pictureBoxMain is System.Windows.Controls.Image.
You can freeze the BitmapSource so that it can be accessed from any thread:
void CamProc_NewTargetPosition(IntPoint Center, System.Drawing.Bitmap image)
{
IntPtr hBitMap = image.GetHbitmap();
BitmapSource bmaps = Imaging.CreateBitmapSourceFromHBitmap(hBitMap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
bmaps.Freeze();
Dispatcher.BeginInvoke((Action)(() =>
{
labelX.Content = String.Format("X: {0}", Center.X);
labelY.Content = String.Format("Y: {0}", Center.Y);
pictureBoxMain.Source = bmaps;
}), DispatcherPriority.Render, null);
}
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
精彩评论