Aleksei Petrenko
Aleksei Petrenko

Reputation: 7178

Correct way to download image Windows Phone 8

I have found it difficult to solve quite simple task: how to download image from my remote server?

The easiest way to do it is just:

BitmapImage img = new BitmapImage(new Uri("http://myserv/test.jpg", UriKind.Absolute));
xamlImageContainer.Source = img;

but I think this solution is not ideal, because it can block UI thread (can it?). So I decided to use "async" approach:

async void LoadImage()
{
    xamlImageContainer.Source = await Task.Run(() =>
    {
        return new BitmapImage(new Uri("http://myserv/test.jpg", UriKind.Absolute));
    });
}

But on the line return new BitmapImage I got UnauthorizedAccessException which says "invalid cross-thread access"! What is wrong here, please suggest.

Upvotes: 0

Views: 1344

Answers (2)

MattyMerrix
MattyMerrix

Reputation: 11193

Yes @anderZubi is correct. CreateOptions is the best solution for this problem, however, if you want to load something from a background thread to the UI thread. You need to call the Dispatcher. Dispatcher.BeginInvoke(() => YourMethodToUpdateUIElements());

This will call the method on the UI thread and you will not get AccessViolationException.

Just FYI.

Upvotes: 1

anderZubi
anderZubi

Reputation: 6424

Objects of BitmapImage type can only be crated in UI thread. Hence the "invalid cross-thread access".

However, you can set BitmapImage's CreateOptions property to BackgroundCreation. That way the image is downloaded and decoded in a background thread:

img.CreateOptions = BitmapCreateOptions.BackgroundCreation;

Upvotes: 1

Related Questions