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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With