Click here to Skip to main content
15,868,145 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: (untagged)
Gents,
in short, I'm surprised how can I update GUI from another thread started by a Task? See below example.
Sure that is a fake Async implementation but ignore that now...
Question how that works well even I expected Exceptions as GUI updated not from the GUI thread?
So, could somebody confirm is it a good way, and what makes that work?
Thanks!

What I have tried:

the binding:

<textblock text="{Binding Name}">

the view:

class Person : INotifyPropertyChanged
    {
        private string _name;
        public void Run()
        {
            //do something long...
            Name = "karoly";
        }
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
                OnPropertyChanged("Name");
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }


the application:


Person person;
       public MainWindow()
       {
           InitializeComponent();
           person= new Person();
           this.DataContext = person;
           person.Name = "unknown";

       }

       private async void RunButton_Click(object sender, RoutedEventArgs e)
       {
           Task t = new Task(person.Run);
           t.Start();
           await t;

       }
Posted
Updated 15-Feb-21 9:10am
Comments
[no name] 12-Feb-21 7:42am    
I think this will answer your question, see accepted answer:
multithreading - WPF Databinding thread safety? - Stack Overflow[^]
Member 11704751 12-Feb-21 8:11am    
thanks embarkadero
some comments really suggests that data automatically marshalled to GUI , but not for collcetions...
[no name] 12-Feb-21 10:07am    

1 solution

as Embarkadero suggested , Microsoft say that supported by WPF:
Quote:
Accessing collections on non-UI Threads
WPF enables you to access and modify data collections on threads other than the one that created the collection. This enables you to use a background thread to receive data from an external source, such as a database, and display the data on the UI thread. By using another thread to modify the collection, your user interface remains responsive to user interaction.


Thanks Embarkadero!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900