Reputation: 182
I wan't to know the best method to load image asynchronously from Mysql in a WPF application.
Thanks.
Upvotes: 2
Views: 583
Reputation: 29632
Use the ThreadPool
to load the image from the database.
On the ThreadPool
, queue the load of the image from the database;
When the image is loaded, still in the thread pool, convert the image into an ImageSource
using BitmapFrame.Create()
;
Using Dispather.Invoke
, set the Image
property to the loaded image.
So, something like this:
private void button1_Click(object sender, RoutedEventArgs e)
{
ThreadPool.QueueUserWorkItem(LoadImage, new LoadImageRequest { ImageName = "Image.png", Control = image1 });
}
private void LoadImage(object state)
{
var request = (LoadImageRequest)state;
byte[] data = ...; // load bytes from the database using request.ImageName
using (var stream = new MemoryStream(data))
{
var imageSource = BitmapFrame.Create(stream);
Dispatcher.BeginInvoke(
new Action<ImageSource>(p => request.Control.Source = p), imageSource
);
}
}
private class LoadImageRequest
{
public string ImageName;
public Image Control;
}
Upvotes: 2