title: Chaining Task.Factory.FromAsync and ContinueWith vs. await
body: <p>Consider an MVC4 / NET 4.5 asynchronous action method that has two IO-bound, in-order operations to do, both of which follow the IAsyncResult pattern.  Below I've created a simple example using the System.DirectoryServices.Protocols namespace.  Although I've long been a fan of the TPL and other async models in .NET (as well as callback-heavy models like node.js), I'm finally getting around to async/await.</p>
  
  <p>As shown with 'await', it returns the proper result, but I've been confounded on a way to get the same result with .ContinueWith and Task.Factory.FromAsync, the latter which usefully relieves the code of the mess of dealing with IAsyncResult or the syntactical mess of callbacks.  </p>
  
  <p>Maybe my sample code is already doing things in the most optimal way? .ContinueWith seems like the more idiomatic approach (or is it?) but I could not find any way to chain a new Task as a continuation; a Func continuation isn't going to cut it here without devolving.</p>
  
  <pre><code>public async Task&lt;ActionResult&gt; AjaxStuff()
      {
          var c = new LdapConnection(string.Empty);
  
          var t1 = Task.Factory.FromAsync&lt;string&gt;(
              c.BeginSendRequest(new SearchRequest(string.Empty, "(&amp;(objectClass=*))", SearchScope.Base, "defaultNamingContext"), PartialResultProcessing.NoPartialResultSupport, null, null),
              iar =&gt;
              {
                  return ((SearchResponse)c.EndSendRequest(iar)).Entries[0].Attributes["defaultNamingContext"][0].ToString();
              });
  
          var nc = await t1;
  
          var t2 = Task.Factory.FromAsync&lt;string&gt;(
              c.BeginSendRequest(new SearchRequest(nc, "(&amp;(givenName=steve))", SearchScope.Subtree), PartialResultProcessing.NoPartialResultSupport, null, null),
              iar =&gt;
              {
                  var result = (SearchResponse)c.EndSendRequest(iar);
                  return result.Entries.Count &gt; 0 ? result.Entries[0].DistinguishedName : "no such thing";
              });
  
          return this.PartialView("AjaxStuff", await t2);
      }
  </code></pre>