Skip to content

Instantly share code, notes, and snippets.

@bymyslf
Last active September 20, 2016 10:51
Show Gist options
  • Save bymyslf/d3647d125ad8d07fd967bbf16ceae42c to your computer and use it in GitHub Desktop.
Save bymyslf/d3647d125ad8d07fd967bbf16ceae42c to your computer and use it in GitHub Desktop.
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