简体   繁体   English

在 BackgroundWorker 和主线程之间共享对象

[英]Sharing objects between a BackgroundWorker and main thread

I have a ListBox object in my main thread (WPF application).我的主线程(WPF 应用程序)中有一个 ListBox object。 Why am I not able to access it in BackgroundWorker thread.为什么我无法在 BackgroundWorker 线程中访问它。 As far as I know, the stack is separate for each thread, but the heap is common.据我所知,每个线程的堆栈都是分开的,但堆是通用的。 Isn't ListBox object created in heap. ListBox object 不是在堆中创建的。 In that case why is it not accessible.在那种情况下,为什么它无法访问。 I tried passing the ListBox reference as parameter and tried to access its contents in the BackgroundWorker.我尝试将 ListBox 引用作为参数传递,并尝试在 BackgroundWorker 中访问其内容。 Is the concept of sharing objects between threads different from C++?线程间共享对象的概念和C++有区别吗?

Like WinForms, the design of WPF is greatly simplified by the requirement that all user interface elements be accessed only from the threads that created them.与 WinForms 一样,WPF 的设计通过要求所有用户界面元素只能从创建它们的线程访问而大大简化。

When you are trying to write a multi-threaded program, this "feature" can seem to be a grave limitation.当您尝试编写多线程程序时,此“功能”似乎是一个严重的限制。 It is impossible to modify even the simplest properties of a user interface element directly from a background thread.直接从后台线程修改用户界面元素的最简单属性也是不可能的。 If so, how can we use background threads at all with WPF?如果是这样,我们如何在 WPF 中使用后台线程?

The answer is that we must transform our actions intended for the user interface onto the foreground thread where the work can be performed without conflict.答案是我们必须将针对用户界面的操作转换到前台线程,在前台线程中可以无冲突地执行工作。 More strictly speaking, we must have our actions execute in the context of the thread that created the element we are trying to modify.更严格地说,我们必须让我们的动作在创建我们试图修改的元素的线程的上下文中执行。

The topic of threading in WPF is a large one but here is an excellent introductory article: WPF 中的线程主题很大,但这里有一篇很棒的介绍性文章:

If you read this article you'll see how to use the Dispatcher to accomplish your actions without violating the threading model.如果您阅读本文,您将了解如何使用Dispatcher来完成您的操作而不违反线程 model。

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

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