Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronously Loading a BitmapImage in C# using WPF

Tags:

c#

wpf

What's the best way to asynchronously load an BitmapImage in C# using WPF?

like image 898
user3837 Avatar asked Aug 31 '08 10:08

user3837


2 Answers

To elaborate onto aku's answer, here is a small example as to where to set the IsAsync:

ItemsSource="{Binding IsAsync=True,Source={StaticResource ACollection},Path=AnObjectInCollection}"

That's what you would do in XAML.

like image 93
kevindaub Avatar answered Oct 10 '22 13:10

kevindaub


This will allow you to create the BitmapImage on the UI thread by using the HttpClient to do the async downloading:

private async Task<BitmapImage> LoadImage(string url)
{
    HttpClient client = new HttpClient();

    try
    {
        BitmapImage img = new BitmapImage();
        img.CacheOption = BitmapCacheOption.OnLoad;
        img.BeginInit();
        img.StreamSource = await client.GetStreamAsync(url);
        img.EndInit();
        return img;
    }
    catch (HttpRequestException)
    {
        // the download failed, log error
        return null;
    }
}
like image 22
David Avatar answered Oct 10 '22 11:10

David