Reputation: 2411
I'm somewhat new to WPF but my understanding is by default a WPF app has 2 threads; one for UI and one for management. Correct?
Say in my MainWindow
spawns other windows in there own thread. So I create a new thread, and in that thread I create an instance of Foo1
(defined as class Foo1 : Window
). Then create another thread, and create an instance of Foo2, etc. (I do this with the thinking that since each of these windows do some intensive things perhaps they should be on their own thread).
I suppose my question is two folds:
a) is this overkill or should I simply instantiate Foo1
, Foo2
, Foo3
from MainWindow
all in the same thread.
b) if it's not overkill, how do I safely update my UI. Do changes to UI elements within each of the respective Window
need to be placed in a Dispatcher
to get onto the singular UI thread?
Upvotes: 1
Views: 911
Reputation: 32715
a) Generally it is overkill. All of the very large WPF applications I've seen have been built with just a single UI thread, so in the general case I'd say it's not necessary. It's possible you may find a special case to use one, but if you were constantly using new threads I'd suggest there might be a design problem.
I have used a second UI thread in the past when my main window was doing a lot of work that had to be done on the dispatcher, and I wanted a responsive loading indicator. In that case, I created a second window on its own thread with the indicator, and positioned it over the top. But 99% of the time it shouldn't be needed.
b) That's correct. Every Window (in fact, every object derived from DispatcherObject) has a Dispatcher property that will give you access to the dispatcher for the current window. You'll find that when calling code to update another window, you'll have to get the dispatcher for that window and invoke it.
Upvotes: 1