Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Load Image in Background Thread in Silverlight WP7

0.00/5 (No votes)
22 Jul 2013 1  
Load image in background thread in Silverlight WP7.

Load image at background thread in Silverlight Windows Phone 7 application, is that possible?

Usually when you try to use BitmapImage, Image, WriteableImage in other than UI thread, you'll get exception. This is because these classes are derived from  System.Windows.Threading.DispatcherObject, which is blocked access from other than UI thread. There exists an extension to WriteableBitmap, LoadJpeg, which is works fine in thread, but you have to create WriteableBitmap object on main UI thread.

using System.Windows;  
using System.Windows.Media.Imaging;  
using System.IO;  
using System.Threading;  
  
namespace ImageHelpers  
{  
    public delegate void ImageLoadedDelegate(WriteableBitmap wb, object argument);  
  
    public class ImageThread  
    {  
        public event ImageLoadedDelegate ImageLoaded;  
  
        public ImageThread()  
        {  
        }  
  
        public void LoadThumbAsync(Stream src, WriteableBitmap bmp, object argument)  
        {  
            ThreadPool.QueueUserWorkItem(callback =>  
            {  
                bmp.LoadJpeg(src);  
                src.Dispose();  
                if (ImageLoaded != null)  
                {  
                    Deployment.Current.Dispatcher.BeginInvoke(() =>  
                    {  
                        ImageLoaded(bmp, argument);  
                    });  
                }  
            });  
        }  
    }  
}

Using scenario:

ImageThread imageThread = new ImageThread();  
  
private void Init()  
{  
    imageThread.ImageLoaded += LoadFinished;  
}  
  
void LoadFinished(WriteableBitmap bmp, object arg)  
{  
    Imgage1.Source = bmp;  
}  
  
void DeferImageLoading( Stream imgStream )  
{  
    // we have to give size  
    var bmp = new WriteableBitmap(80, 80);  
    imageThread.LoadThumbAsync(imgStream, bmp, this);  
} 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here