Skip to content

Instantly share code, notes, and snippets.

@dgrunwald
Created March 2, 2012 20:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgrunwald/1961071 to your computer and use it in GitHub Desktop.
Save dgrunwald/1961071 to your computer and use it in GitHub Desktop.
Awaitable WPF Dispatcher
public static class WpfExtensions
{
public static DispatcherAwaiter GetAwaiter(this Dispatcher dispatcher)
{
return new DispatcherAwaiter(dispatcher, DispatcherPriority.Normal);
}
public static Tuple<Dispatcher, DispatcherPriority> WithPriority(this Dispatcher dispatcher, DispatcherPriority priority)
{
return Tuple.Create(dispatcher, priority);
}
public static DispatcherAwaiter GetAwaiter(this Tuple<Dispatcher, DispatcherPriority> tuple)
{
return new DispatcherAwaiter(tuple.Item1, tuple.Item2);
}
public struct DispatcherAwaiter : System.Runtime.CompilerServices.INotifyCompletion
{
readonly Dispatcher dispatcher;
readonly DispatcherPriority priority;
public DispatcherAwaiter(Dispatcher dispatcher, DispatcherPriority priority)
{
if (dispatcher == null)
throw new ArgumentNullException("dispatcher");
this.dispatcher = dispatcher;
this.priority = priority;
}
public DispatcherAwaiter WithPriority(DispatcherPriority priority)
{
return new DispatcherAwaiter(dispatcher, priority);
}
public bool IsCompleted { get { return false; } }
public void GetResult() { }
public void OnCompleted(Action continuation)
{
dispatcher.BeginInvoke(priority, continuation);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment