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 )
{
var bmp = new WriteableBitmap(80, 80);
imageThread.LoadThumbAsync(imgStream, bmp, this);
}