title: .NET async\await fundamentals
body: <p>After playing with .NET 4.5 async\await framework I have a question.</p>
  
  <p>Let's look at this program (<a href="http://msdn.microsoft.com/en-us/library/hh191443.aspx" rel="nofollow">the msdn example</a>):</p>
  
  <pre><code>    async Task&lt;int&gt; AccessTheWebAsync()
      {
          HttpClient client = new HttpClient();
  
          Task&lt;string&gt; getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
  
          DoIndependentWork();
  
          string urlContents = await getStringTask;
  
          return urlContents.Length;
      }
  
  
      void DoIndependentWork()
      {
          resultsTextBox.Text += "Working . . . . . . .\r\n";
      }
  </code></pre>
  
  <p>The program will run in this order:</p>
  
  <ol>
  <li>new HttpClient.</li>
  <li>GetStringAsync invoke synchronously.</li>
  <li>In some point, GetStringAsync calls await and the control return to AccessTheWebAsync.</li>
  <li>DoIndependentWork invoked.</li>
  <li>The program waits the string to be returned (blocks if the operation didn't complete).</li>
  <li>return the length of the urlContent.</li>
  </ol>
  
  <p>One thing that took me a while to understand is that the method <code>GetStringAsync</code> runs synchronously despite its name (the name convention is really misleading).</p>
  
  <p>In oreder to run the method asynchronously, we need to use <code>Task.Run</code> or <code>Task.Factory.StartNew</code> explicitly.</p>
  
  <p>But the real question is, if we have independent work, why not do it right away rather then waiting the await to be called from GetStringAsync? (In other words, why async methods doesn't run asynchronously by definition?)</p>
  
  <p><strong>EDIT:</strong>
  I'll rephrase the second and third operations:</p>
  
  <p>(2) GetStringAsync start synchronously.</p>
  
  <p>(3) In some point, GetStringAsync calls await and the thread forks, the control return to AccessTheWebAsync.</p>