Create BitmapFrame asynchronously in an async meth

2020-05-01 10:23发布

Anyone knows how to create BitmapFrame asynchronously in WPF?

I want to batch print XAML Image element whose Source property is set code behind. Here LogoImageUrl is the URL of the web image I want to load asynchronously.

LogoImage.Source = BitmapFrame.Create(new Uri(LogoImageUrl));

Can I create an async method like this:

public async Task<BitmapFrame> GetBitmapFrame(Uri uri)
{
    await ... // What to be awaited?

    return BitmapFrame.Create(uri);
}

...so I can use that method in a try block and then print it in finally block?

1条回答
相关推荐>>
2楼-- · 2020-05-01 11:12

You should asynchronously download the web image and create a BitmapFrame from the downloaded buffer:

public async Task<BitmapFrame> GetBitmapFrame(Uri uri)
{
    var httpClient = new System.Net.Http.HttpClient();
    var buffer = await httpClient.GetByteArrayAsync(uri);

    using (var stream = new MemoryStream(buffer))
    {
        return BitmapFrame.Create(
            stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
    }
}

Since the BitmapFrame.Create call in the above example return a frozen BitmapFrame, you may also create the BitmapFrame asynchronously (although I doubt it's necessary).

public async Task<BitmapFrame> GetBitmapFrame(Uri uri)
{
    var httpClient = new System.Net.Http.HttpClient();
    var buffer = await httpClient.GetByteArrayAsync(uri);

    return await Task.Run(() =>
    {
        using (var stream = new MemoryStream(buffer))
        {
            return BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
        }
    });
}
查看更多
登录 后发表回答