Error: The calling thread cannot access this object because a different thread owns it

雨燕双飞 提交于 2019-12-02 07:08:49

问题


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

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


回答1:


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

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

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

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

OR

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

BmpImg.Freeze()


来源:https://stackoverflow.com/questions/20954966/error-the-calling-thread-cannot-access-this-object-because-a-different-thread-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!