获取错误调用线程无法访问此对象,因为另一个线程拥有它wpf,如何使用Dispatch.invovef
我试图捕捉位图图像并在bitmapsource中显示,我使用了如下转换方法获取错误调用线程无法访问此对象,因为另一个线程拥有它wpf,如何使用Dispatch.invovef,wpf,Wpf,我试图捕捉位图图像并在bitmapsource中显示,我使用了如下转换方法 [System.Runtime.InteropServices.DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); private BitmapSource Bitmap2BitmapImage(Bitmap bitmap) { BitmapImage retval; try {
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
private BitmapSource Bitmap2BitmapImage(Bitmap bitmap)
{
BitmapImage retval;
try
{
retval = Imaging.CreateBitmapSourceFromHBitmap(
bitmap.GetHbitMap(),
IntPtr.Zero,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
}
finally
{
DeleteObject(hBitmap)
}
return retval;
}
显示图像的代码如下所示
Bitmap bmp= (Bitmap)e.frame.clone();
imgPic.source= imageconversion(bmp);
我用谷歌搜索了这个错误…我开始了解dispatch.invoke方法。请建议我如何在我的代码中使用dispatcher,该dispatcher可以通过
System.Threading.ThreadStart
的新实例调用,该实例获取一个lambda表达式,其中包含要在UI线程上执行的代码。确保使用Application.Current.Dispatcher
而不是Dispatcher.Current
,因为后者不一定返回UI线程
Application.Current.Dispatcher.Invoke(
DispatcherPriority.Input,
new ThreadStart(() =>
{
// Do something
}));
请在你的回答中添加一些解释。谢谢你的解答。但是我没有得到这个开始…在名称空间中有必要吗???