In .NET, Windows 8 and Windows Phone 7 I have code similar to this:
public static void InvokeIfRequired(this Dispatcher dispatcher, Action action) { if (
With the advent of the TPL. I came up with a slightly improved version of the accepted answer which returns a task and can be await'ed using the new async and await keywords.
public Task RunAsync(Action action) { TaskCompletionSource taskCompletionSource = new TaskCompletionSource(); if (this.synchronizationContext == SynchronizationContext.Current) { try { action(); taskCompletionSource.SetResult(null); } catch (Exception exception) { taskCompletionSource.SetException(exception); } } else { // Run the action asyncronously. The Send method can be used to run syncronously. this.synchronizationContext.Post( (obj) => { try { action(); taskCompletionSource.SetResult(null); } catch (Exception exception) { taskCompletionSource.SetException(exception); } }, null); } return taskCompletionSource.Task; }