Remco1250
Remco1250

Reputation: 85

C# WPF change ImageSource Image on Thread

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:

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?

Upvotes: 1

Views: 1804

Answers (1)

Clemens
Clemens

Reputation: 128136

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

Upvotes: 4

Related Questions