I need to run some code that talked to a server on a background worker however the result of the call would update a collection and a view on the UI, so would need to marshall back to the UI thread.
Based on the article at http://sachabarber.net/?p=411 I took this and tweaked it a little to be able to run part on the background and part on the UI thread in a single call.
public static void InvokeIfRequired(this DispatcherObject control, Action methodcall)
{
if (control.Dispatcher.Thread != Thread.CurrentThread)
control.Dispatcher.Invoke(DispatcherPriority.Normal, methodcall);
else
methodcall();
}
public static void RunInBackground(Action backgroundAction, DispatcherObject control, Action uiAction)
{
BackgroundWorker bgWorker = new BackgroundWorker
{
WorkerReportsProgress = true, WorkerSupportsCancellation = false
};
bgWorker.DoWork += (s, e) =>
{
backgroundAction();
if (uiAction != null)
control.InvokeIfRequired(uiAction);
};
bgWorker.RunWorkerAsync();
}
Then the call can become:
PageHelper.RunInBackground(
() =>
{
// Background thread code
}, this,
() =>
{
// UI thread code
});
}
which I think is quite neat.