I am new to C# and .Net and I have some doubts regarding WPF thread safety and how different WPF pages should communicate with each other. My main project would have a class called MainWindow.cs
with MainWndow.xaml
. In addition, I will have two pages called Page1.cs
with Page1.xaml
and Page2.cs
with Page2.xaml
. Reading the documentation, I know that each WPF page has its own thread and all the controls of WPF should only be accessed through the same thread , in case I have one background thread in the same page, I can access the controls of WPF in background thread through following example
controlName.Dispacher.Invoke(()=>updateControl())
My question is if the same operation, I want to do from Page1.cs
class by changing for example
the textbox either on MainWndow.xaml
or Page2.xaml
. How can be done these operations safely?
CodePudding user response:
Reading the documentation, I know that each WPF page has its own thread
This is incorrect, or at least misleading. Each WPF control has a thread that owns said control, and all access has to be done from this thread. But in the majority of cases, it is the same thread that owns all controls. So there is no concern about thread safety.
It is possible to have multiple windows that are owned by different UI threads, but this is rarely recommended just because all the issues with thread safety and synchronization.
So, unless you are doing something uncommon, you should only need to care if you are running things on the single UI thread, or a background thread.
CodePudding user response:
Try to look at INotifyPropertyChanged and I would also suggest taking a look at MVVM Pattern if you are going to do some projects with WPF