title: Limit asp.net request execution time
body: <p>I have ASP.NET 4 handler that must response less than 50 ms. In some situations, e.g call to remote services, it hang for longer time. </p>
  
  <p>Is it possible to kill (maybe in IIS) such requests longer than 50 ms? </p>
  
  <p>There are about 1000 requests per seccond, if I wrap every request in separate task with timeout then iis worker process queue increase extremly fast and hung all system. It happens after iisrestart or when we have a lot of timeouts to remote services.
  
  
  <p><strong>UPD:</strong> This is API handler that handles requests from other services (servers) </p>
  
  <p><strong>UPD2:</strong> I have tryed wrap request in separate task with timeout, but in doesn't work when there are many requests per second. It's too expensive to create separate task even with threadpool</p>
  
  <p>TimeoutFunctionWrapper:</p>
  
  <pre><code>public static T Execute&lt;T&gt;(Func&lt;T&gt; func, int timeout)
  {
      object sync = new object();
      bool isCompleted = false;
  
      WaitCallback watcher = obj =&gt; {
          Thread watchedThread = obj as Thread;
  
          lock (sync)
          {
              if (!isCompleted)
              {
                  Monitor.Wait(sync, timeout);
              }
          }
  
          if (!isCompleted)
          {
              watchedThread.Abort();
          }
      };
  
      try
      {
          ThreadPool.QueueUserWorkItem(watcher, Thread.CurrentThread);
          return func();
      }
      catch (ThreadAbortException)
      {
          // This is our own exception.
          Thread.ResetAbort();
          return default(T);
      }
      finally
      {
          lock (sync)
          {
              isCompleted = true;
              Monitor.Pulse(sync);
          }
      }
  }
  </code></pre>