title: Synchronously waiting for an async operation, and why does Wait() freeze the program here
body: <p><strong>Preface</strong>: I'm looking for an explanation, not just a solution. I already know the solution.</p>
  
  <p>Despite having spent several days studying MSDN articles about the Task-based Asynchronous Pattern (TAP), async and await, I'm still a bit confused about some of the finer details.</p>
  
  <p>I'm writing a logger for Windows Store Apps, and I want to support both asynchronous and synchronous logging. The asynchronous methods follow the TAP, the synchronous ones should hide all this, and look and work like ordinary methods.</p>
  
  <p>This is the core method of asynchronous logging:</p>
  
  <pre><code>private async Task WriteToLogAsync(string text)
  {
      StorageFolder folder = ApplicationData.Current.LocalFolder;
      StorageFile file = await folder.CreateFileAsync("log.log",
          CreationCollisionOption.OpenIfExists);
      await FileIO.AppendTextAsync(file, text,
          Windows.Storage.Streams.UnicodeEncoding.Utf8);
  }
  </code></pre>
  
  <p>Now the corresponding synchronous method...</p>
  
  <p><strong>Version 1</strong>:</p>
  
  <pre><code>private void WriteToLog(string text)
  {
      Task task = WriteToLogAsync(text);
      task.Wait();
  }
  </code></pre>
  
  <p>This looks correct, but it does not work. The whole program freezes forever.</p>
  
  <p><strong>Version 2</strong>:</p>
  
  <p>Hmm.. Maybe the task was not started?</p>
  
  <pre><code>private void WriteToLog(string text)
  {
      Task task = WriteToLogAsync(text);
      task.Start();
      task.Wait();
  }
  </code></pre>
  
  <p>This throws <code>InvalidOperationException: Start may not be called on a promise-style task.</code></p>
  
  <p><strong>Version 3:</strong></p>
  
  <p>Hmm.. <code>Task.RunSynchronously</code> sounds promising.</p>
  
  <pre><code>private void WriteToLog(string text)
  {
      Task task = WriteToLogAsync(text);
      task.RunSynchronously();
  }
  </code></pre>
  
  <p>This throws <code>InvalidOperationException: RunSynchronously may not be called on a task not bound to a delegate, such as the task returned from an asynchronous method.</code></p>
  
  <p><strong>Version 4 (the solution):</strong></p>
  
  <pre><code>private void WriteToLog(string text)
  {
      var task = Task.Run(async () =&gt; { await WriteToLogAsync(text); });
      task.Wait();
  }
  </code></pre>
  
  <p>This works. So, 2 and 3 are the wrong tools. But 1? What's wrong with 1 and what's the difference to 4? What makes 1 cause a freeze? Is there some problem with the task object? Is there a non-obvious deadlock?</p>