Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ivan-danilov
Last active October 18, 2015 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivan-danilov/3ee430522d596ccf6496 to your computer and use it in GitHub Desktop.
Save ivan-danilov/3ee430522d596ccf6496 to your computer and use it in GitHub Desktop.
/// <summary>
/// Executes passed task (probably result of async method call) on a Dispatcher as
/// synchronous one, but without Wait() and risk of deadlock, using new dispatcher frame
/// that is finished as a continuation of passed task.
///
/// You should still await the task returned back if you want correct exception propagation.
///
/// Note that you can execute this method only if you're in a WPF dispatcher's context,
/// otherwise it will throw an exception.
/// </summary>
public static Task ExecuteSynchronouslyOnDispatcher(this Task task)
{
if (!(SynchronizationContext.Current is DispatcherSynchronizationContext))
throw new InvalidOperationException("This method should be called only from UI thread");
var dispatcherFrame = new DispatcherFrame();
task.ContinueWith(_ => { dispatcherFrame.Continue = false; });
Dispatcher.PushFrame(dispatcherFrame);
return task;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment