使用此代码,使用必须等到所有图像都加载完毕。我想异步将这些图像加载到列表框中,这样用户就不必等了。我该怎么做?
public photos()
{
InitializeComponent();
refreshView();
}
private void refreshView()
{
string[] fileNames = storage.GetFileNames();
for (int i = 0; i < fileNames.Length; i++)
{
image = new Image();
FileStream jpegStream = storage.OpenFile(fileNames[i], FileMode.Open, FileAccess.Read);
image.Source = PictureDecoder.DecodeJpeg(jpegStream, 200, 200);
jpegStream.Dispose();
photoList.Items.Add(image);
}
}
答案 0 :(得分:3)
您可以使用BackgroundWorker
。
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (o, args) =>
{
//now you have a choice: get all images and add when all are retrieved,
//or get images asynchronously here too...
//probably best to do the latter:
string[] fileNames = storage.GetFileNames();
Parallell.ForEach(fileNames, file =>
{
Image image = new Image();
using(FileStream jpegStream = storage.OpenFile(fileNames[i], FileMode.Open, FileAccess.Read))
{
image.Source = PictureDecoder.DecodeJpeg(jpegStream, 200, 200);
}
Dispatcher.BeginInvoke(() => photoList.Items.Add(image));
}
};
bw.RunWorkerAsync();