title: Task.Run vs null SynchronizationContext
body: <p>In an ASP.NET 4.5 application, which of these is better for calling an async method from a sync method?</p>
  
  <pre><code>var result = Task.Run(() =&gt; SomethingAsync()).GetAwaiter().GetResult();
  
  // or 
  
  var temp = SynchronizationContext.Current;
  try
  {
      SynchronizationContext.SetSynchronizationContext(null);
      return SomethingAsync().GetAwaiter().GetResult();
  }
  finally
  {
      SynchronizationContext.SetSynchronizationContext(temp);
  }
  </code></pre>
  
  <p><strong>Note:</strong> Yes, I know I should be using <code>async/await</code> all the way down, but I'm asking about the very bottom, and outside of ASP.NET Core the filters and razor views are not async, so if I want to call an async method from a filter or a razor view, I need to sync it some way. Just using <code>SomethingAsync().GetAwaiter().GetResult()</code> leads to a deadlock, because of the <code>SynchronizationContext</code>, so I need a way to run this code without a <code>SynchronizationContext</code>.</p>
  
  <p><strong>EDIT</strong>
  Here is the simple helper class that wraps this up cleanly:</p>
  
  <pre><code>public static class Async
  {
      public static T Run&lt;T&gt;(Func&lt;Task&lt;T&gt;&gt; func)
      {
          var context = SynchronizationContext.Current;
          if (context == null)
          {
              return func().GetAwaiter().GetResult();
          }
  
          SynchronizationContext.SetSynchronizationContext(null);
  
          try
          {
              return func().GetAwaiter().GetResult();
          }
          finally
          {
              SynchronizationContext.SetSynchronizationContext(context);
          }
      }
  
      public static void Run(Func&lt;Task&gt; func)
      {
          var context = SynchronizationContext.Current;
          if (context == null)
          {
              func().GetAwaiter().GetResult();
              return;
          }
  
          SynchronizationContext.SetSynchronizationContext(null);
  
          try
          {
              func().GetAwaiter().GetResult();
          }
          finally
          {
              SynchronizationContext.SetSynchronizationContext(context);
          }
      }
  }
  
  // Example
  var result = Async.Run(() =&gt; GetSomethingAsync("blabla"));
  </code></pre>