Download BitmapImage using Task Parallel Library

2019-08-08 16:16发布

问题:

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.

My current method is the following:

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

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

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

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?

回答1:

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

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.

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