title: Threadpool deadlock with Task.Result
body: <p>We have a large legacy with asp.net system, we have started using some async methods from an infrastructure library that we cannot change.
  The system doesn't use tasks in most places but the infrastructure exposes only async methods.</p>
  
  <p>In the code we use the following pattern to use the async methods:</p>
  
  <p><code>Task.Run(() =&gt; Foo()).Result</code></p>
  
  <p>We use the <a href="https://msdn.microsoft.com/en-us/library/hh160382(v=vs.110).aspx" rel="noreferrer">Task.Run</a> to prevent a deadlock if somewhere in the code someone didn't use ConfigureAwait(false), There are a lot of places that someone could have missed and it has happened before.
  And we use <a href="https://msdn.microsoft.com/en-us/library/dd321468(v=vs.110).aspx" rel="noreferrer">Task.Result</a> to integrate it with the existing sync code base.</p>
  
  <p>After experiencing heavy load We've noticed that that we are getting timeouts but the servers are not doing any work(Low CPU), we've found out that when there are a lot of calls to the server and the thread pool reaches the maximal number of threads the threads reach a deadlock in the Task.Result as it blocks the thread until the task is finished but the task can't run as there are no thread pool threads available to run it.</p>
  
  <p>The best solution would be to change the code to work async all the way, but that is not an option right now.
  Also removing the Task.Run could work but it's too risky as there is not enough test coverage to know that we will not cause new deadlocks in untested flows. </p>
  
  <p>I've tried to implement a new task scheduler that will not use the thread pool but a different set of threads to run the Foo task, but internal task are being executed on the default task scheduler that I do not want to replace.</p>
  
  <p>Any ideas how this can be resolved without a huge change to the code base?</p>
  
  <p>This is a small sample app that reproduces the issue, using only 10 threads and not the real limit. In the sample Foo will never be called.</p>
  
  <pre><code>class Program
  {
      static void Main(string[] args)
      {
          ThreadPool.SetMaxThreads(10, 10);
          ThreadPool.SetMinThreads(10, 10);
  
          for (int i = 0; i &lt; 10; i++)
          {
              ThreadPool.QueueUserWorkItem(CallBack);
          }
  
          Console.ReadKey();
      }
  
      private static void CallBack(object state)
      {
          Thread.Sleep(1000);
  
          var result = Task.Run(() =&gt; Foo()).Result;
      }
  
      public static async Task&lt;string&gt; Foo()
      {
          await Task.Delay(100);
          return "";
      }
  }
  </code></pre>