Following Jason Dolinger video I’ve crated DispatchingWcfModel that decorates normal model. But I don’t understand why do I need it. Should I always use some kind of Dispatching model? What if I will use normal model instead of dispatching model? Why do I need “Dispatcher”?
class DispatchingWcfModel : IWcfModel
{
private readonly IWcfModel _underlying;
private readonly Dispatcher _currentDispatcher;
public DispatchingWcfModel(IWcfModel model)
{
_currentDispatcher = Dispatcher.CurrentDispatcher;
_underlying = model;
_underlying.DataArrived += _underlying_DataArrived;
}
private void _underlying_DataArrived(List<ConsoleData> obj)
{
Action dispatchAction = () =>
{
if (DataArrived != null)
{
DataArrived(obj);
}
};
_currentDispatcher.BeginInvoke(DispatcherPriority.DataBind, dispatchAction);
}
public List<ConsoleData> DataList
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public event Action<List<ConsoleData>> DataArrived;
}
TL;DR:
DispatchingWcfModelclass wrap up injectedIWcfModeland guarantee that when a new data comes – changes would be dispatched to UI in safe way eventIWcfModel.DataArrivedevent has been raised in background thread, soDispatchingWcfModelalways pushes callback using Dispatcher to the UI Thread.More detailed: In your example
DispatchingWcfModelclass subscribing to an event of injectedIWcfModel, so when event has been raised – event handler_underlying_DataArrivedwould be called and what most important point – it would be called on the thread which actually raising an event so it is possible that calling thread would not be a UI Thread so any changes to UI controls would be failed, to avoid this Dispatched is used.In WPF Dispatcher is useful when you need to update UI elements so this should be done in UI Thread. Right way to do this – delegate this work to Dispatcher which persitsting a queue of workitems (requests) which should be performed on the UIThread.
MSDN: