For your question about providing a sample, if there is a worker class like...
public class Worker
{
public Worker(Action<string>action)
{
Task.Run(() =>
{
int i = 0;
while (true)
{
++i;
Task.Run(() => { action("Current value " + i); });
Task.Run(() =>
{
// doing some work here
});
Thread.Sleep(1000);
}
});
}
}
...which is performing background work on different threads and advising the caller via the delegate. The delegate is a plain vanilla Action
that takes a string. Then the View Model should be implemented such that it does not care on which thread the message originated. Here's the corresponding code in the VM...
private readonly SynchronizationContext _context = SynchronizationContext.Current;
private void StartWorker()
{
Worker w = new Worker((s) => _context.Post(delegate { StatusText = s; }, null));
}
This code uses a SynchronizationContext, but could just as easily use a dispatcher. The point being that the responsibility for sync'ing up on the UI thread doesn't belong to a worker. The worker shouldn't care, and similarly the VM is thread-agnostic and posts everything via its SynchronizationContext.
The code for the StatusText property looks like this...
private string _statusText;
public string StatusText
{
[DebuggerStepThrough]
get { return _statusText; }
[DebuggerStepThrough]
set
{
if (value != _statusText)
{
_statusText = value;
OnPropertyChanged("StatusText");
}
}
}
And finally, on the UI, it is presented like this...
<StatusBar DockPanel.Dock="Bottom">
<TextBlock Text="{Binding StatusText}"/>
</StatusBar>
...
So to recap your questions: the worker threads can access it, but they should not have to deal with sync'ing up the UI. That responsibility is the VM's. And VM should be thread-agnostic and sync the UI through the dispatcher or synchronization context or other methods.
Scheduling through the Dispatcher is appropriate if you are manipulating a collection that is the subject of a binding (e.g., an ObservableCollection); otherwise SynchronizationContext is appropriate (it's a bit more light-weight).