4

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.

Selva
  • 1,310
  • 2
  • 14
  • 31

1 Answers1

2

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.

usr
  • 168,620
  • 35
  • 240
  • 369
  • Are you mean to say that UI thread can update all of its UI element, even though the UI elements(textbox ,button etc...) Dispatcher object is differ from UI thread Dispatcher object? If so, say, for textbox1, I can update textbox1 by two ways , 1. By UI thread Dispatcher object and 2. By textbox1 Dispatcher object. please correct me. – Selva Jun 18 '15 at 09:15
  • I don't know about the case of multiple dispatchers. Usually, there is one dispatcher per thread. I don't know if this can ever be different. Even if it can that seems like a needless complication. The general rule is, you need to invoke on the dispatcher that owns the object if you are not on that dispatcher's thread right now. – usr Jun 18 '15 at 09:18