获取错误调用线程无法访问此对象,因为另一个线程拥有它 wpf,如何使用 Dispatch.invovef

Getting error The calling thread cannot access this object because a different thread owns it wpf, How to use Dispatch.invovef

我正在尝试捕获位图图像并在位图源中显示我使用的转换方法如下

 [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);

我有 google 这个错误...我开始了解 dispatch.invoke 方法。请建议我如何在我的代码中使用

可以使用 System.Threading.ThreadStart 的新实例调用调度程序,该实例获取包含要在 UI 线程上执行的代码的 lambda 表达式。确保使用 Application.Current.Dispatcher 而不是 Dispatcher.Current,因为后者不一定 return UI 线程。

Application.Current.Dispatcher.Invoke(
    DispatcherPriority.Input, 
    new ThreadStart(() => 
    { 
        // Do something 
    }));