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++?
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:
If you read this article you'll see how to use the Dispatcher
to accomplish your actions without violating the threading model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With