【发布时间】:2021-08-21 10:49:30
【问题描述】:
我正在尝试在后台线程中加载 BitmapImage,然后将 (WPF) 图像源设置为此 BitmapImage。
我目前正在尝试这样的事情:
public void LoadPicture()
{
Uri filePath = new Uri(Directory.GetCurrentDirectory() + "/" + picture.PictureCacheLocation);
if (Visible && !loaded)
{
if (File.Exists(filePath.AbsolutePath) && picture.DownloadComplete)
{
BitmapImage bitmapImage = LoadImage(filePath.AbsolutePath);
image.Dispatcher.Invoke(new Action<BitmapImage>((btm) => image.Source = btm), bitmapImage);
loaded = true;
}
}
}
但我得到一个InvalidOperationException,因为后台线程拥有 BitmapImage。 有没有办法将 BitmapImage 的所有权或副本提供给 UI 线程?
我需要在后台线程中加载位图图像,因为它可能会阻塞很长时间。
【问题讨论】:
-
使用
async/await而不是摆弄Invoke。这自 2012 年以来就没有必要了。此外,仅当后台线程调用LoadPicture或LoadImage使用线程时,bitmapImage才会由后台线程拥有。贴出缺少的代码 -
此外,您可以创建一个
BitmapImage,直接使用var bitmapImage=new BitmapImage(filePath);从文件中加载数据。使用Path.Combine而不是直接连接字符串 -
由于代码使用的是 current 文件夹,因此无需连接。
var filePath=new Uri(Path.GetAbsolutePath(picture.PictureCacheLocation)); -
类似于this 的东西可能有用。冻结并从 Task 操作返回 BitmapImage
-
另外,
picture.DownloadComplete似乎表明您首先下载图像,然后将其写入文件,然后从该文件创建 BitmapImage。请注意,您可以直接从远程 URL 创建 BitmapImage。
标签: c# wpf multithreading bitmapimage invalidoperationexception