Skip to content

Instantly share code, notes, and snippets.

@DamienBraillard
Created September 19, 2018 08:19
Show Gist options
  • Save DamienBraillard/e101265b91fe766fa02b3b905d00290c to your computer and use it in GitHub Desktop.
Save DamienBraillard/e101265b91fe766fa02b3b905d00290c to your computer and use it in GitHub Desktop.
Calling async code from WPF event handlers synchronously
// BEWARE: There is no universal way to synchronously wait for async tasks. This can be used in a WPF context only.
private static void RunSynchronously(Func<Task> func)
{
// Gets the awaiter for the task
var awaiter = func().ConfigureAwait(false).GetAwaiter();
// Creates a new dispatcher frame that will lock (like Window.ShowDialog()) but with the message pump still running
// The dispatcher frame terminates only when the task to wait for has completed
DispatcherFrame frame = new DispatcherFrame();
awaiter.OnCompleted(() => frame.Continue = false);
Dispatcher.PushFrame(frame);
// Call GetResult for the sake of not swallowing exceptions (ok here as we know the task has not yet completed).
awaiter.GetResult();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment