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)
public static void RunInBackground(Action backgroundAction, DispatcherObject control, Action uiAction)
BackgroundWorker bgWorker = new BackgroundWorker
WorkerReportsProgress = true, WorkerSupportsCancellation = false
bgWorker.DoWork += (s, e) =>
if (uiAction != null)
Then the call can become:
// Background thread code
// UI thread code
which I think is quite neat.