Click here to Skip to main content
15,886,689 members
Articles / Mobile Apps / Windows Phone 7
Technical Blog

Load Image in Background Thread in Silverlight WP7

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
22 Jul 2013CPOL 7.9K   4  
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.

C#
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:

C#
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(8080);  
    imageThread.LoadThumbAsync(imgStream, bmp, this);  
} 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) i-BLADES
Thailand Thailand
I'm Android and Full Stack Software Engineer. 28 years in software industry, lots of finished projects. I’m never afraid of learning something new and you can see it by amount of skills in my resume.

I'm working remotely since 2009, self-motivated and self-organized.

There are no impossible projects. I have experience with Android, iOS, Web, Desktop, Embedded applications, VR, AR, XR, Computer vision, Neural networks, Games, IoT, you name it.

Comments and Discussions

 
-- There are no messages in this forum --