gpt4 book ai didi

WPF/BackgroundWorker 和 BitmapSource 问题

转载 作者:行者123 更新时间:2023-12-04 17:28:39 24 4
gpt4 key购买 nike

我是 WPF 的初学者,正在尝试一个家庭项目以熟悉该技术。我有一个简单的表单,用户可以在其中选择一个图像文件,然后显示 EXIF 数据和图像的缩略图。这工作正常,但是当我选择一个 RAW 图像文件(~9 MB)时,拇指加载可能会有轻微的延迟,所以我想我可以使用 BackgroundWorker 来解码图像,用户可以查看 EXIF 数据,然后当图像被解码后,它就会显示出来。

BitmapSource 对象在 BackgroundWorkers DoWork 方法中声明:

worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
string filePath = args.Argument as string;

BitmapDecoder bmpDecoder = BitmapDecoder.Create(new Uri(filePath), BitmapCreateOptions.None, BitmapCacheOption.None);
BitmapSource bmpSource = bmpDecoder.Frames[0];
bmpSource.Freeze(); //As suggested by Paul Betts

args.Result = bmpSource;
};

我遇到的问题是当我尝试在 RunWorkerCompleted 方法中设置我的 Image 控件的源时,我收到一个错误,因为该对象由另一个线程拥有。
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
imgThumb.Source = args.Result as BitmapSource;
};

我尝试使用 imgThumb.Dispatcher.BeginInvoke()设置源的方法,但这也不起作用,我猜是因为它是 args.Result由另一个线程拥有,而不是 imgThumb ?我怎样才能解决这个问题?

可能是我的 Dispatcher 编码错误(以下是内存中的,我删除了我拥有的)。
imgThumb.Dispatcher.Invoke(new Action<BitmapSource>(
delegate(BitmapSource src)
{
imgThumb.Source = src;
}
), bmpSource);

欢迎任何建议或想法。

更新

将我的 DoWork 方法更改为使用 BitmapCreateOptions.None 而不是 .DelayCreation 但现在我在加载 RAW 文件时出现以下错误(迄今为止我测试过的只有佳能 .CR2 文件),该代码适用于 jpg 文件。这可能是我安装的佳能编解码器的问题,以允许我显示 RAW 文件吗?

The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))

最佳答案

在 BitmapSource 上调用 Freeze() 就不会出现这个问题(Freezing 摆脱了线程限制,但使对象不可变)

关于WPF/BackgroundWorker 和 BitmapSource 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2128438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com