There are times when we need to delegate a block of codes through dispatcher. If the code is in code behind of a window's or usercontrol's code then it is simple because then we can just call this.Dispatcher.Invoke to pass the code block. However what if the code is in the ViewModel. In order to use the MVVM pattern we should in fact put code in view model and avoid coding in code behind file.
So when there is a need to execute code in UI thread, we should use dispatcher as
App.Current.Dispatcher.Invoke.
If UI thread executing codes in view model, there is no need to use delegate (though dispatcher invoke). However if code in view model is being executed in another thread other than the UI thread and if it is updating any object that was created in UI thread, then we need to execute this code (one in another thread) through a dispatcher delegate in order to update object that was created in UI thread.
For example, let us say we are updating an ObservableCollection object that was instantiated in UI thread and then we created a "task" and within which we are trying to update that ObservableCollection object.
public ObservableCollection<Trade> LoadedTrades = new ObservableCollection<Trade>();
public void LoadTradesData()
{
TaskFactory taskfac = new TaskFactory();
taskfac.StartNew(() =>
{
var tradelist = Trades.LoadTradesFromDataSource();
App.Current.Dispatcher.Invoke(new Action(() =>
{
LoadedTrades.Clear();
foreach (var trade in tradelist)
LoadedTrades.Add(trade);
}));
});
}
No comments:
Post a Comment