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. }  

No comments:

Post a Comment