简体   繁体   English

对WPF中非UI对象的跨线程访问

[英]Cross-thread access to non-ui object in wpf

I'm having some problems using a backgroundworker in a WPF app. 我在WPF应用程序中使用backgroundworker时遇到一些问题。 Here's the situation: 情况如下:

I'm trying to do two things. 我正在尝试做两件事。 First scanning a number of images and then use barcode recognition on the scanned images. 首先扫描许多图像,然后在扫描的图像上使用条形码识别。 I'm retrieving the scanned images as a list of BitmapSource objects and these should be available to my backgroundworker thread. 我将扫描的图像作为BitmapSource对象的列表进行检索,并且这些应可用于我的backgroundworker线程。

After some googling it seems most solutions are specific to communication with ui elements on the main thread because none of the solutions I've found have worked for me. 经过一番谷歌搜索后,似乎大多数解决方案都是特定于与主线程上的ui元素进行通信的,因为我发现的所有解决方案都不适合我。 I've tried using delegates and the dispatcher but to no avail. 我尝试使用委托和调度程序,但无济于事。

I need the BitmapSources to create Bitmaps with them which is the input of the barcode recognition. 我需要BitmapSources与它们一起创建位图,这是条形码识别的输入。

Thanks, 谢谢,

Kevin 凯文

In WPF, all DispatcherObjects (not only UI elements) can be accessed only from the thread that created them. 在WPF中,只能从创建它们的线程访问所有DispatcherObjects (不仅是UI元素)。 BitmapSource inherits (indirectly) from DispatcherObject , so it follows this rule. BitmapSource (间接)继承自DispatcherObject ,因此它遵循此规则。 However, it also inherits from Freezable , and Freezable objects can be accessed from another thread if they are frozen . 但是,它也继承自Freezable如果 Freezable对象被冻结,则可以从另一个线程访问它们

So, after your BitmapSource is initialized, you can call Freeze on it, and it will be accessible from other threads. 因此,在初始化BitmapSource之后,您可以对其调用Freeze ,并且可以从其他线程访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM