Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing objects between a BackgroundWorker and main thread

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 image 833
softwarematter Avatar asked May 30 '11 02:05

softwarematter


1 Answers

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.

like image 90
Rick Sladkey Avatar answered Oct 13 '22 19:10

Rick Sladkey