我正在尝试将多个图像异步加载到 ui 中。
加载图像时(从路径创建位图),应将图像设置为窗口上矩形的填充。
当我将位图图像的创建也放在 Dispatcher.Invoke 方法中时,代码就可以工作了。但显然我希望在胎面而不是在调用中完成繁重的工作(创建位图)。
我尝试了几种解决方案,包括 backgroundworker,但我无法让它工作。现在我有以下代码:
private void Window_ContentRendered(object sender, EventArgs e)
{
Thread loadThread = new Thread(new ThreadStart(LoadImagesAsync));
loadThread.Start();
}
private void LoadImagesAsync()
{
IEnumerable<string> images = System.IO.Directory.GetFiles(IMAGE_FOLDER, "*.jpg").Skip(_PageNumber * NUMBER_OF_IMAGES).Take(NUMBER_OF_IMAGES);
for (int i = 0; i < NUMBER_OF_IMAGES; i++)
{
var bitm = new BitmapImage(new Uri(images.ElementAt(i)));
this.Dispatcher.Invoke(() =>
{
Grid grid = (Grid)grd_photoBox.Children[i];
var rectangle = (from e in grid.Children.OfType<Rectangle>()
where e is Rectangle
select e).First();
ImageBrush brush = new ImageBrush(bitm);
rectangle.Fill = brush;
});
}
}
我得到以下异常:
The calling thread cannot access this object because a different thread owns it.
有什么线索吗?