Sep 6, 2011

Load Image at 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.


  1. using System.Windows;  
  2. using System.Windows.Media.Imaging;  
  3. using System.IO;  
  4. using System.Threading;  
  5.   
  6. namespace ImageHelpers  
  7. {  
  8.     public delegate void ImageLoadedDelegate(WriteableBitmap wb, object argument);  
  9.   
  10.     public class ImageThread  
  11.     {  
  12.         public event ImageLoadedDelegate ImageLoaded;  
  13.   
  14.         public ImageThread()  
  15.         {  
  16.         }  
  17.   
  18.         public void LoadThumbAsync(Stream src, WriteableBitmap bmp, object argument)  
  19.         {  
  20.             ThreadPool.QueueUserWorkItem(callback =>  
  21.             {  
  22.                 bmp.LoadJpeg(src);  
  23.                 src.Dispose();  
  24.                 if (ImageLoaded != null)  
  25.                 {  
  26.                     Deployment.Current.Dispatcher.BeginInvoke(() =>  
  27.                     {  
  28.                         ImageLoaded(bmp, argument);  
  29.                     });  
  30.                 }  
  31.             });  
  32.         }  
  33.     }  
  34. }  


Using scenario:

  1. ImageThread imageThread = new ImageThread();  
  2.   
  3. private void Init()  
  4. {  
  5.     imageThread.ImageLoaded += LoadFinished;  
  6. }  
  7.   
  8. void LoadFinished(WriteableBitmap bmp, object arg)  
  9. {  
  10.     Imgage1.Source = bmp;  
  11. }  
  12.   
  13. void DeferImageLoading( Stream imgStream )  
  14. {  
  15.     // we have to give size  
  16.     var bmp = new WriteableBitmap(80, 80);  
  17.     imageThread.LoadThumbAsync(imgStream, bmp, this);  
  18. }  

3 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from .Net Core Training in Chennai. or learn thru .Net Core Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Es6 Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete
  2. With the Internet, nearly everything has been a great deal simpler. Correspondences were streamlined. Examining for articles and answers is less demanding than it was previously.best background investigation service

    ReplyDelete