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