在异步方法中异步创建BitmapFrame [英] Create BitmapFrame asynchronously in an async method

查看:158
本文介绍了在异步方法中异步创建BitmapFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道如何在WPF中异步创建BitmapFrame吗?

Anyone knows how to create BitmapFrame asynchronously in WPF?

我想批量打印XAML Image元素,该元素的Source属性设置在后面. LogoImageUrl是我要异步加载的网络图像的URL.

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

我可以创建这样的async方法:

Can I create an async method like this:

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

    return BitmapFrame.Create(uri);
}

...所以我可以在try块中使用该方法,然后在finally块中打印它?

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

推荐答案

您应该异步下载Web图像并从下载的缓冲区中创建BitmapFrame:

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


由于上述示例中的BitmapFrame.Create调用返回了冻结的BitmapFrame,因此您也可以异步创建BitmapFrame(尽管我怀疑这是必要的).


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

这篇关于在异步方法中异步创建BitmapFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆