1

I'm trying to update an ImageSource with an image on runtime from a different thread then the main_UI one, but for some reason i keep getting:
The calling thread cannot access this object because a different thread owns it.
I have tried a few things:

  • im_Cover.Dispatcher.Invoke(() => { if (im_Cover.Source != image) im_Cover.Source = image; });
  • Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { im_Cover.Source = image; }));
  • Freezing the image (which was not possible). I tried to add a messagebox on the error and once the error showed up and I pressed OK, for some reason, the image did load.
  • Tried using a custom downloadcompleted eventhandler which didn't even fire.

Here's my code:

for (int i = 1; i < correctArtist.images.Count; i++)
{
if (correctArtist.images[i].width > correctArtist.images[biggest].width)
   biggest = i;
}
Image biggestImage = correctArtist.images[biggest];
var imgUrl = biggestImage.url;

image = new BitmapImage(new Uri(imgUrl));


bool uiAccessCover = im_Cover.Dispatcher.CheckAccess();
if (uiAccessCover)
{
    im_Cover.Source = image;
}
else
{
    //im_Cover.Dispatcher.Invoke(() => { if (im_Cover.Source != image) im_Cover.Source = image; });
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => { im_Cover.Source = image; }));
}

And for some reason this: lb_Song.Dispatcher.Invoke(() => { if ((string)lb_Song.Content != song) lb_Song.Content = song; }); does work.

Any idea why it doesn't work, and how I can fix this?

1 Answer 1

4

Before passing a BitmapImage from a background thread to the UI thread by e.g.

im_Cover.Dispatcher.BeginInvoke(new Action(() => im_Cover.Source = image)); 

it must be frozen. Otherwise it must also be created on the UI thread, like

im_Cover.Dispatcher.BeginInvoke(new Action(() =>
    im_Cover.Source = new BitmapImage(new Uri(imgUrl))));
Sign up to request clarification or add additional context in comments.

1 Comment

You sir, are a lifesaver. Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.