Skip to content

Instantly share code, notes, and snippets.

@jrgcubano
Created March 3, 2015 23:21
Show Gist options
  • Save jrgcubano/ffce66cd532c5a00dae3 to your computer and use it in GitHub Desktop.
Save jrgcubano/ffce66cd532c5a00dae3 to your computer and use it in GitHub Desktop.
Await, SynchronizationContext WPF
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