title: REST WCF service locks thread when called using AJAX in an ASP.Net site
body: <p>I have a WCF REST service consumed in an ASP.Net site, from a page, using AJAX.</p>
  
  <p>I want to be able to call methods from my service async, which means I will have callback handlers in my javascript code and when the methods finish, the output will be updated. The methods should run in different threads, because each method will take different time to complete their task</p>
  
  <p>I have the code semi-working, but something strange is happening because the first time I execute the code <strong>after compiling, it works</strong>, <em>running each call in a different threads</em> but subsequent calls  blocs the service, in such a way that each method call has to wait until the last call ends in order to execute the next one. And they are running on the same thread. I have had the same problem before when I was using <em>Page Methods</em>, and I solved it by disabling the session in the page but I have not figured it out how to do the same when consuming WCF REST services</p>
  
  <p>Note: Methods complete time (running them async should take only <strong>7 sec</strong> and the result should be: <strong>Execute1 - Execute3 - Execute2</strong>)</p>
  
  <ul>
  <li><code>Execute1</code> --> 2 sec</li>
  <li><code>Execute2</code> --> 7 sec</li>
  <li><code>Execute3</code> --> 4 sec</li>
  </ul>
  
  <h3>Output After compiling</h3>
  
  <p><img src="https://i.stack.imgur.com/gQ1eK.png" alt="after compiling"></p>
  
  <h3>Output subsequent calls (this is the problem)</h3>
  
  <p><img src="https://i.stack.imgur.com/evJu6.png" alt="subsequent calls"></p>
  
  <p>I will post the code...I'll try to simplify it as much as I can</p>
  
  <h3>Service Contract</h3>
  
  <pre><code>[ServiceContract(
      SessionMode = SessionMode.NotAllowed
  )]
  public interface IMyService
  {
      // I have other 3 methods like these: Execute2 and Execute3
      [OperationContract]
      [WebInvoke(
          RequestFormat = WebMessageFormat.Json,
          ResponseFormat = WebMessageFormat.Json,
          UriTemplate = "/Execute1",
          Method = "POST")]
      string Execute1(string param);
  }
  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  [ServiceBehavior(
      InstanceContextMode = InstanceContextMode.PerCall
  )]
  public class MyService : IMyService
  {
      // I have other 3 methods like these: Execute2 (7 sec) and Execute3(4 sec)
      public string Execute1(string param)
      {
          var t = Observable.Start(() =&gt; Thread.Sleep(2000), Scheduler.NewThread);
          t.First();
  
          return string.Format("Execute1 on: {0} count: {1} at: {2} thread: {3}", param, "0", DateTime.Now.ToString(), Thread.CurrentThread.ManagedThreadId.ToString());
      }
   }
  </code></pre>
  
  <h3>ASPX page</h3>
  
  <pre><code>&lt;%@ Page EnableSessionState="False" Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
      CodeBehind="Default.aspx.cs" Inherits="RestService._Default" %&gt;
  &lt;asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"&gt;
      &lt;script type="text/javascript"&gt;
          function callMethodAsync(url, data) {
              $("#message").append("&lt;br/&gt;" + new Date());
              $.ajax({
                  cache: false,
                  type: "POST",
                  async: true,
                  url: url,
                  data: '"de"',
                  contentType: "application/json",
                  dataType: "json",
                  success: function (msg) {
                      $("#message").append("&lt;br/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;" + msg);
                  },
                  error: function (xhr) {
                      alert(xhr.responseText);
                  }
              });
          }
          $(function () {
              $("#callMany").click(function () {
                  $("#message").html("");
                  callMethodAsync("/Execute1", "hello");
                  callMethodAsync("/Execute2", "crazy");
                  callMethodAsync("/Execute3", "world");
              });
          });
      &lt;/script&gt;
  &lt;/asp:Content&gt;
  &lt;asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"&gt;
      &lt;input type="button" id="callMany" value="Post Many" /&gt;
      &lt;div id="message"&gt;
      &lt;/div&gt;
  &lt;/asp:Content&gt;
  </code></pre>
  
  <h3>Web.config (relevant)</h3>
  
  <pre><code>&lt;system.webServer&gt;
    &lt;modules runAllManagedModulesForAllRequests="true" /&gt;
  &lt;/system.webServer&gt;
    &lt;system.serviceModel&gt;
      &lt;serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /&gt;
      &lt;standardEndpoints&gt;
        &lt;webHttpEndpoint&gt;
          &lt;standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" /&gt;
        &lt;/webHttpEndpoint&gt;
      &lt;/standardEndpoints&gt;
    &lt;/system.serviceModel&gt;
  </code></pre>
  
  <h3>Global.asax</h3>
  
  <pre><code>    void Application_Start(object sender, EventArgs e)
      {
          RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");
          RouteTable.Routes.Add(new ServiceRoute("", 
            new WebServiceHostFactory(), 
            typeof(MyService)));
      }
  </code></pre>
  
  <h2>Edit 1</h2>
  
  <p>I have tried several combinations but the result is the same, I was testing using Visual Studio but now I am testing on IIS 7, and it's the same result</p>
  
  <p>I have tried combinations of the following properties:</p>
  
  <pre><code>[ServiceBehavior(
      InstanceContextMode = InstanceContextMode.PerCall,
      ConcurrencyMode = ConcurrencyMode.Multiple
  )]
  </code></pre>
  
  <p>Also I removed the use of Rx, now I am just simulating long-process operations like this:</p>
  
  <pre><code>Thread.Sleep(2000);
  </code></pre>
  
  <p>But the result is the same.... <strong>After compiling, and deploying, (the first call) the service works correctly, it is executed on different threads giving the desired result, but subsequent calls run on the same thread.... I do not get it</strong></p>
  
  <p>I just noticed something, the first time after compiling works, and <strong>the last thread used</strong> is always the thread used on subsequent calls, and this thread is blocked, it's like if the other threads weren't disposed or something or if the last thread were blocked for some reason</p>
  
  <h2>Edit 2</h2>
  
  <p>This is the full code of this project (RestWCF.zip)</p>
  
  <p><a href="http://sdrv.ms/P9wW6D" rel="nofollow noreferrer">http://sdrv.ms/P9wW6D</a></p>