Last active
September 20, 2016 10:51
-
-
Save bymyslf/d3647d125ad8d07fd967bbf16ceae42c to your computer and use it in GitHub Desktop.
This file contains 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; | |
public static class TaskExtensions | |
{ | |
public static T RunTaskSynchronously<T>(this Task<T> task) | |
{ | |
using (NoSynchronizationContextScope.Enter()) | |
{ | |
return task.Result; | |
} | |
} | |
//http://stackoverflow.com/a/28307965/6618364 | |
private static class NoSynchronizationContextScope | |
{ | |
public static Disposable Enter() | |
{ | |
var synchronizationContext = SynchronizationContext.Current; | |
SynchronizationContext.SetSynchronizationContext(null); | |
return new Disposable(synchronizationContext); | |
} | |
public struct Disposable : IDisposable | |
{ | |
private readonly SynchronizationContext synchronizationContext; | |
public Disposable(SynchronizationContext synchronizationContext) | |
{ | |
this.synchronizationContext = synchronizationContext; | |
} | |
public void Dispose() | |
{ | |
SynchronizationContext.SetSynchronizationContext(this.synchronizationContext); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment