title: How to make a WCF REST method entirely asynchronous with the Task Parallel Library?
body: <p>I am trying to make a WCF REST method entirely asynchronous (I don't want to block anywhere). Essentially I have a simple service with 3 layers: Service, Business Logic and Data Access Layer. The Data Access Layer is accessing a database and it can take several second to get a response back from that method. </p>
  
  <p>I don't understand very well how to chaining of all those method work. Can someone please help me to complete the sample I am trying to write below? I don't understand well the pattern used by WCF and I didn't find much documentation on the subject.</p>
  
  <p>Can someone help me to complete the following example? In addition, how can I measure that the service will be able to handle more load than a typical synchronous implementation?</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Runtime.Remoting.Messaging;
  using System.ServiceModel;
  using System.ServiceModel.Activation;
  using System.ServiceModel.Web;
  using System.Threading.Tasks;
  
  namespace WcfRestService1
  {
      [ServiceContract]
      [AspNetCompatibilityRequirements(RequirementsMode = 
          AspNetCompatibilityRequirementsMode.Allowed)]
      [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
      public class Service1
      {
          private BusinessLogic bll = new BusinessLogic();
  
          // Synchronous version
          [WebGet(UriTemplate = "/sync")]
          public string GetSamples()
          {
              return bll.ComputeData();
          }
  
          // Asynchronous version - Begin
          [WebGet(UriTemplate = "/async")]
          [OperationContract(AsyncPattern = true)]
          public IAsyncResult BeginGetSampleAsync(AsyncCallback callback, 
              object state)
          {
              Task&lt;string&gt; t = bll.ComputeDataAsync();
  
              // What am I suppose to return here
              // return t.AsyncState; ???
          }
  
          // Asynchronous version - End
          public List&lt;SampleItem&gt; EndGetSampleAsync(IAsyncResult result)
          {
              // How do I handle the callback here?
          }
      }
  
      public class BusinessLogic
      {
          public Task&lt;string&gt; ComputeDataAsync()
          {
              DataAccessLayer dal = new DataAccessLayer();
              return dal.GetData();
          }
  
          public string ComputeData()
          {
              Task&lt;string&gt; t = this.ComputeDataAsync();
  
              // I am blocking... Waiting for the data
              t.Wait();
  
              return t.Result;
          }
      }
  
      public class DataAccessLayer
      {
          public Task&lt;string&gt; GetData()
          {
              // Read data from disk or network or db
          }
      }
  }
  </code></pre>