Created
September 19, 2018 08:19
-
-
Save DamienBraillard/e101265b91fe766fa02b3b905d00290c to your computer and use it in GitHub Desktop.
Calling async code from WPF event handlers synchronously
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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