在BackgroundWorker和主线程之间共享对象 [英] Sharing objects between a BackgroundWorker and main thread

查看:122
本文介绍了在BackgroundWorker和主线程之间共享对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主线程(WPF应用程序)中有一个ListBox对象.为什么我无法在BackgroundWorker线程中访问它.据我所知,每个线程的堆栈都是独立的,但是堆是常见的.不是在堆中创建ListBox对象.在这种情况下,为什么无法访问它.我尝试将ListBox引用作为参数传递,并尝试在BackgroundWorker中访问其内容.线程之间共享对象的概念不同于C ++吗?

I have a ListBox object in my main thread (WPF application). Why am I not able to access it in BackgroundWorker thread. As far as I know, the stack is separate for each thread, but the heap is common. Isn't ListBox object created in heap. 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. Is the concept of sharing objects between threads different from C++?

推荐答案

像WinForms一样,WPF的设计大大简化了,因为要求仅从创建它们的线程访问所有用户界面元素.

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.

当您尝试编写多线程程序时,此功能"似乎是一个严重的限制.甚至无法直接从后台线程修改用户界面元素的最简单属性.如果是这样,我们如何在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?

答案是,我们必须将用于用户界面的操作转换到前台线程,在该线程上可以无冲突地执行工作.更严格地说,我们必须在创建要修改的元素的线程的上下文中执行操作.

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.

WPF中的线程主题很大,但这是一篇出色的入门文章:

The topic of threading in WPF is a large one but here is an excellent introductory article:

如果您阅读本文,您将了解如何使用Dispatcher完成操作而不违反线程模型.

If you read this article you'll see how to use the Dispatcher to accomplish your actions without violating the threading model.

这篇关于在BackgroundWorker和主线程之间共享对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆