Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading an image in a background thread in WPF

Tags:

wpf

There are a bunch of questions about this already on this site and other forums, but I've yet to find a solution that actually works.

Here's what I want to do:

  • In my WPF app, I want to load an image.
  • The image is from an arbitrary URI on the web.
  • The image could be in any format.
  • If I load the same image more than once, I want to use the standard windows internet cache.
  • Image loading and decoding should happen synchronously, but not on the UI Thread.
  • In the end I should end up with something that I can apply to an <Image>'s source property.

Things I have tried:

  • Using WebClient.OpenRead() on a BackgroundWorker. Works fine, but doesn't use the cache. WebClient.CachePolicy only affects that particular WebClient instance.
  • Using WebRequest on the Backgroundworker instead of WebClient, and setting WebRequest.DefaultCachePolicy. This uses the cache properly, but I've not seen an example that doesn't give me corrupted-looking images half the time.
  • Creating a BitmapImage in a BackgroundWorker, setting BitmapImage.UriSource and trying to handle BitmapImage.DownloadCompleted. This seems to use the cache if BitmapImage.CacheOption is set, but there doesn't seem to be away to handle DownloadCompleted since the BackgroundWorker returns immediately.

I've been struggling with this off-and-on for literally months and I'm starting to think it's impossible, but you're probably smarter than me. What do you think?

like image 206
Josh Santangelo Avatar asked Mar 25 '11 23:03

Josh Santangelo


2 Answers

I have approached this problem in several ways, including with WebClient and just with BitmapImage.

EDIT: Original suggestion was to use the BitmapImage(Uri, RequestCachePolicy) constructor, but I realized my project where I tested this method was only using local files, not web. Changing guidance to use my other tested web technique.

You should run the download and decoding on a background thread because during loading, whether synchronous or after download the image, there is a small but significant time required to decode the image. If you are loading many images, this can cause the UI thread to stall. (There are a few other intricacies here like DelayCreation but they don't apply to your question.)

There are a couple ways to load an image, but I've found for loading from the web in a BackgroundWorker, you'll need to download the data yourself using WebClient or a similar class.

Note that BitmapImage internally uses a WebClient, plus it has a lot of error handling and settings of credentials and other things that we'd have to figure out for different situations. I'm providing this snippet but it has only been tested in a limited number of situations. If you are dealing with proxies, credentials, or other scenarios you'll have to massage this a bit.

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, e) =>
{
    Uri uri = e.Argument as Uri;

    using (WebClient webClient = new WebClient())
    {
        webClient.Proxy = null;  //avoids dynamic proxy discovery delay
        webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
        try
        {
            byte[] imageBytes = null;

            imageBytes = webClient.DownloadData(uri);

            if (imageBytes == null)
            {
                e.Result = null;
                return;
            } 
            MemoryStream imageStream = new MemoryStream(imageBytes);
            BitmapImage image = new BitmapImage();

            image.BeginInit();
            image.StreamSource = imageStream;
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.EndInit();

            image.Freeze();
            imageStream.Close();

            e.Result = image;
        }
        catch (WebException ex)
        {
            //do something to report the exception
            e.Result = ex;
        }
    }
};

worker.RunWorkerCompleted += (s, e) =>
    {
        BitmapImage bitmapImage = e.Result as BitmapImage;
        if (bitmapImage != null)
        {
            myImage.Source = bitmapImage;
        }
        worker.Dispose();
    };

worker.RunWorkerAsync(imageUri);

I tested this in a simple project and it works fine. I'm not 100% about whether it is hitting the cache, but from what I could tell from MSDN, other forum questions, and Reflectoring into PresentationCore it should be hitting the cache. WebClient wraps WebRequest, which wraps HTTPWebRequest, and so on, and the cache settings are passed down each layer.

The BitmapImage BeginInit/EndInit pair ensures that you can set the settings you need at the same time and then during EndInit it executes. If you need to set any other properties, you should use the empty constructor and write out the BeginInit/EndInit pair like above, setting what you need before calling EndInit.

I typically also set this option, which forces it to load the image into memory during EndInit:

image.CacheOption = BitmapCacheOption.OnLoad;

This will trade off possible higher memory usage for better runtime performance. If you do this, then the BitmapImage will be loaded synchronously within EndInit, unless the BitmapImage requires async downloading from a URL.

Further notes:

BitmapImage will async download if the UriSource is an absolute Uri and is an http or https scheme. You can tell whether it is downloading by checking the BitmapImage.IsDownloading property after EndInit. There are DownloadCompleted, DownloadFailed, and DownloadProgress events, but you have to be extra tricky to get them to fire on the background thread. Since BitmapImage only exposes an asynchronous approach, you would have to add a while loop with the WPF equivalent of DoEvents() to keep the thread alive until the download is complete. This thread shows code for DoEvents that works in this snippet:

worker.DoWork += (s, e) =>
    {
        Uri uri = e.Argument as Uri;
        BitmapImage image = new BitmapImage();

        image.BeginInit();
        image.UriSource = uri;
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.UriCachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
        image.EndInit();

        while (image.IsDownloading)
        {
            DoEvents(); //Method from thread linked above
        }
        image.Freeze();
        e.Result = image;
    };

While the above approach works, it has a code smell because of DoEvents(), and it doesn't let you configure the WebClient proxy or other things that might help with better performance. The first example above is recommended over this one.

like image 97
Joshua Blake Avatar answered Nov 10 '22 05:11

Joshua Blake


The BitmapImage needs async support for all of its events and internals. Calling Dispatcher.Run() on the background thread will...well run the dispatcher for the thread. (BitmapImage inherits from DispatcherObject so it needs a dispatcher. If the thread that created the BitmapImage doesn't already have a dispatcher a new one will be created on demand. cool.).

Important safety tip: The BitmapImage will NOT raise any events if it is pulling data from cache (rats).

This has been working very well for me....

     var worker = new BackgroundWorker() { WorkerReportsProgress = true };

     // DoWork runs on a brackground thread...no thouchy uiy.
     worker.DoWork += (sender, args) =>
     {
        var uri = args.Argument as Uri;
        var image = new BitmapImage();

        image.BeginInit();
        image.DownloadProgress += (s, e) => worker.ReportProgress(e.Progress);
        image.DownloadFailed += (s, e) => Dispatcher.CurrentDispatcher.InvokeShutdown();
        image.DecodeFailed += (s, e) => Dispatcher.CurrentDispatcher.InvokeShutdown();
        image.DownloadCompleted += (s, e) =>
        {
           image.Freeze();
           args.Result = image;
           Dispatcher.CurrentDispatcher.InvokeShutdown();
        };
        image.UriSource = uri;
        image.EndInit();

        // !!! if IsDownloading == false the image is cached and NO events will fire !!!

        if (image.IsDownloading == false)
        {
           image.Freeze();
           args.Result = image;
        }
        else
        {
           // block until InvokeShutdown() is called. 
           Dispatcher.Run();
        }
     };

     // ProgressChanged runs on the UI thread
     worker.ProgressChanged += (s, args) => progressBar.Value = args.ProgressPercentage;

     // RunWorkerCompleted runs on the UI thread
     worker.RunWorkerCompleted += (s, args) =>
     {
        if (args.Error == null)
        {
           uiImage.Source = args.Result as BitmapImage;
        }
     };

     var imageUri = new Uri(@"http://farm6.static.flickr.com/5204/5275574073_1c5b004117_b.jpg");

     worker.RunWorkerAsync(imageUri);
like image 30
Rusty Avatar answered Nov 10 '22 05:11

Rusty