Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datagrid not refreshed when bound datatable is modified using another thread

Scenario: There is a datagrid bound to datatable in View Model. This datatable reference is injected to Model and it is updated using a background thread.

Result: Datagrid is not immediately refreshed as soon as underlying datatable is updated but if I switch between different tabs then datagrid is showing latest values present in datatable.

like image 337
praveenDM Avatar asked Mar 21 '26 03:03

praveenDM


1 Answers

A common approach would be to start a background task for updating the datatable async and hook up on finishing this operation with .ContinueWith to update the UI.

Task.Factory.StartNew(() => { ..Do the background DataTable update.. })
            .ContinueWith(task => {.. Update the UI.. });



But you have to dispatch the .ContinueWith action into the Main Thread, due to the STA restriction.

Task.Factory.StartNew(() => { ..Do the background DataTable update.. })
                .ContinueWith(task => 
                             {
                                var dispatcher = Application.Current == null
                                     ? Dispatcher.CurrentDispatcher
                                     : Application.Current.Dispatcher;

                                Action action = delegate()
                                                {
                                                    //Update UI (e.g. Raise NotifyPropertyChanged on bound DataTable Property)
                                                 };

                               dispatcher.Invoke(DispatcherPriority.Normal, action);
});



Since the Dispatching operation is a repeating operation I would suggest to put the logic into a ViewModelBase Class to reduce the code like this:

Task.Factory.StartNew(() => ..Do the background DataTable update..)
            .ContinueWith(task => Dispatch(() =>
                {
                    //Update UI
                }));



To Update the UI you can use the common notify of INotifyPropertyChanged to raise the property changed event on the bound datatable.

like image 172
menty Avatar answered Mar 22 '26 16:03

menty