Created
March 3, 2015 23:21
-
-
Save jrgcubano/ffce66cd532c5a00dae3 to your computer and use it in GitHub Desktop.
Await, SynchronizationContext WPF
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
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using System.Windows.Threading; | |
public static class AsyncPump | |
{ | |
public static void Run(Func<Task> func) | |
{ | |
if (func == null) throw new ArgumentNullException("func"); | |
var prevCtx = SynchronizationContext.Current; | |
try | |
{ | |
var syncCtx = new DispatcherSynchronizationContext(); | |
SynchronizationContext.SetSynchronizationContext(syncCtx); | |
var t = func(); | |
if (t == null) throw new InvalidOperationException(); | |
var frame = new DispatcherFrame(); | |
t.ContinueWith(_ => { frame.Continue = false; }, | |
TaskScheduler.Default); | |
Dispatcher.PushFrame(frame); | |
t.GetAwaiter().GetResult(); | |
} | |
finally | |
{ | |
SynchronizationContext.SetSynchronizationContext(prevCtx); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment