Sharing objects between a BackgroundWorker and main thread

落爺英雄遲暮 提交于 2019-12-10 14:58:22

问题


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++?


回答1:


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.

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.

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

  • WPF: Threading Model

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



来源:https://stackoverflow.com/questions/6171881/sharing-objects-between-a-backgroundworker-and-main-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!