Create BitmapFrame asynchronously in an async method

纵然是瞬间 提交于 2019-12-02 11:15:54

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);
        }
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!