How WPF Multi threading works?

288 views Asked by At

I knew the basic building blocks of multithreading in WPF, but I do have a question which is quite confusing me.

WPF applications start with two threads:

one for handling rendering and another for managing the UI.

This sounds good,but the UI thread is bothering me, UI Thread is nothing but a Application thread

The thread that creates a WPF UI element owns the elements and other threads can not interact with the UI elements directly,this is known as thread affinity.

Say,I have two text box and One Button in Myapplication and each text box have their own DispatcherObject ,on button click I'll update the textbox with values,hope this'll be done by the UI Thread.

1.Now,My question is UI Thread is application thread, Button will have their own DispatcherObject and Two Text boxes will have their own DispatcherObject, How this UI thread which has its own DispatcherObject and different from these UI controls DispatcherObject can update the textboxes?

  1. My another question is, If create new textbox in Background thread then can I update this text box from UI thread?

please correct my understanding,I couldn't proceed further.

1

There are 1 answers

2
usr On

Each DispatcherObject is associated with a UI thread. Only that thread can access that particular DispatcherObject. In a sanely architected WPF app there is only one UI thread. All elements are created and accessed there.

You can have multiple UI threads with distinct sets of elements but that would be an esoteric scenario that brings a lot of issues.

If create new textbox in Background thread

That text box would be bound to the background thread and could only be used there. Therefore you could not hook it into the main element tree. It would be useless.