Skip to content

Instantly share code, notes, and snippets.

@HaloFour
Created February 10, 2016 15:17
Show Gist options
  • Save HaloFour/94e6a79e79413bdeddd3 to your computer and use it in GitHub Desktop.
Save HaloFour/94e6a79e79413bdeddd3 to your computer and use it in GitHub Desktop.
SynchronizationContext Awaiter Extension Method
public static class SynchronizationContextExtensions {
public struct SynchronizationContextAwaiter : INotifyCompletion {
private readonly SynchronizationContext context;
public SynchronizationContextAwaiter(SynchronizationContext context) {
this.context = context;
}
public bool IsCompleted {
get { return (context == null); }
}
public void GetResult() { }
public void OnCompleted(Action continuation) {
if (context == null) {
continuation();
}
else {
context.Send(state => continuation(), null);
}
}
}
public static SynchronizationContextAwaiter GetAwaiter(this SynchronizationContext context) {
return new SynchronizationContextAwaiter(context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment