Error: The calling thread cannot access this objec

2019-02-27 03:02发布

问题:

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()