使用任务并行库下载 BitmapImage [英] Download BitmapImage using Task Parallel Library

查看:38
本文介绍了使用任务并行库下载 BitmapImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 UI 线程上的 URI 下载 BitmapImage 会挂断应用程序.为了避免这种情况,我尝试在单独的线程中下载 BitmapImage,想知道是否可以使用 TPL 使其变得简单.

Downloading a BitmapImage from a URI on the UI thread hangs up the application. To avoid this, I'm trying to download the BitmapImage in a separate thread, would like to know if it can be made simple with TPL.

我目前的方法如下:

            Task.Factory.StartNew<BitmapImage>(() => new BitmapImage(myUri) { CacheOption = BitmapCacheOption.OnLoad }, CancellationToken.None, TaskCreationOptions.None, new StaTaskScheduler(1))
        .ContinueWith(t => image1.Source = t.Result, TaskScheduler.FromCurrentSynchronizationContext());

这个问题当然是因为 BitmapImage 不是在与 Image 相同的线程上创建的.

The problem with this is of course the fact, that the BitmapImage wasn't created on the same thread as the Image.

从 URI 加载的 BitmapImage 无法冻结,因此无法正常工作.

The BitmapImage loaded from URI cannot be frozen, so that wouldn't work normally.

目前,我能想到的最简单的方法是从 URI 创建一个流,然后从该流加载位图并在返回之前将其冻结.我相信这应该会创建一个非常臃肿的代码.

Currently, the simplest method I can think of is creating a stream from the URI, then loading the bitmap from that stream and freeze it before returning. That should create a really bloating code I believe.

在尝试显示来自网络的图像时,有没有办法让代码更小(更)和(更)可读?

Is there a way to keep the code small(er) and (more) readable while trying to display an image from the web?

推荐答案

如果图像在 XAML 文件中并且您正在使用绑定来加载它,请将 IsAsync 设置为 true 以异步下载它.

If the image is in an XAML file and you're using binding to load it, set IsAsync to true to download it async.

当然,在图像显示之前提供后备占位符是一种很好的做法.一种方法是使用 PriorityBinding.

Of course, then it is good practice to provide a fallback place-holder before the image shows up. One way to do it is to use PriorityBinding.

如果您必须以编程方式执行此操作,请尝试创建一个异步 ImageSource,然后将 BitmapImage 的源设置为它.

If you must do it programatically, try creating an async ImageSource then setting the BitmapImage's source to it.

这篇关于使用任务并行库下载 BitmapImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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