从Mysql到WPF异步加载图像
答
使用ThreadPool
从数据库加载图像。
在
ThreadPool
,队列从数据库中的图像的负载;当图像加载时,仍然在线程池中,使用
BitmapFrame.Create()
将图像转换为ImageSource
;使用
Dispather.Invoke
,将Image
属性设置为加载的图像。
所以,这样的事情:
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;
}
尼斯的答案,但我忘了说我不能使用调度员(或我不知道怎么做),我加载从图像类。 – cyrianox 2010-11-13 09:49:35
您必须使用调度程序。这是没有办法的。如果您从不同的线程加载图像(异步),只有一种方法可以将图像传回UI,并通过调度程序。这个例子显示了如何。 – 2010-11-13 09:53:44