Created
March 2, 2012 20:30
-
-
Save dgrunwald/1961071 to your computer and use it in GitHub Desktop.
Awaitable WPF Dispatcher
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
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