错误:调用线程无法访问该对象,因为其他线程拥有它 [英] Error: The calling thread cannot access this object because a different thread owns it

查看:183
本文介绍了错误:调用线程无法访问该对象,因为其他线程拥有它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到此错误.这是代码:

I get this error. Here is the code:

    Image image;
    BitmapImage BmpImg;
    MemoryStream ms;

    public void Convert()
    {
        ms = new MemoryStream();
        image.Save(ms, ImageFormat.Jpeg);

        BmpImg = new BitmapImage();
        BmpImg.BeginInit();
        BmpImg.StreamSource = new MemoryStream(ms.ToArray());
        BmpImg.EndInit();
    }

    private void Btn_Click(object sender, RoutedEventArgs e)
    {     
        Dispatcher.Invoke(new Action(() => { Image.Source = BmpImg; }));
    }

如何将System.Drawing.Image转换为BitmapImage并在wpf上显示相同内容?

How to convert a System.Drawing.Image to BitmapImage and display the same on wpf?

推荐答案

BmpImg在后台线程上创建. 您无法绑定到在UI线程以外的线程上创建的Image Source DP对象.

BmpImg is created on background thread. You cannot bind to Image Source DP object which is created on thread other than UI thread.

由于您使用的是Dispatcher,所以我现在假设您如何在UI线程上委派内容.

Since you are using Dispatcher, i assume you now how to delegate stuff on UI thread.

因此,您所需要做的就是通过Dispatcher在UI线程上创建BmpImg.

So all you need to do is put the creation of BmpImg on UI thread as well via Dispatcher.

您也可以像这样获得UI调度程序-App.Current.Dispatcher.

You can get UI dispatcher like this as well - App.Current.Dispatcher.

OR

正如@Clemens在注释中建议的那样,如果在BitmapImage实例上调用Freeze(),则可以跨线程访问它.

As @Clemens suggested in comments, if you call Freeze() on BitmapImage instance, you can access it across threads.

BmpImg.Freeze()

这篇关于错误:调用线程无法访问该对象,因为其他线程拥有它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆