title: How do I pass security principal from my request into a thread in asp.net MVC
body: <p>In my ASP.net MVC application I have a request that does a lot of calculations to return the result.  This works fine on my own servers, but when I move to Azure the connection/request gets closed after 4 minutes so I don't ever get the results back I just get an error.</p>
  
  <p>To resolve this I was planning to run the long calculation in a thread and have the client poll to see when it is done.</p>
  
  <p>I have tried all sorts of ways of doing this (threads, thread pools, tasks and hangfire) but i can't get the security context/principal/identity to pass from my request to my new thread.</p>
  
  <p>Here is some sudo code for what I am doing. (I realize that there should be some better synchronization for multiple requests, but this is sudo code) </p>
  
  <pre><code>    public static void SlowCalculation(params)
      {
          _calculationIsRunning = true;
          var principal = System.Security.Principal.GenericPrincipal.Current;
          if (principal?.IsInRole("MySecurityGroup") ?? false)
          {
              // lots of long calculations
              _resutsAreReady = true;
              _calculationIsRunning = true;
          }
      }
  
      //
      // POST: /Get/
      public ActionResult GetResults(params)
      {
          if (_calculationIsRunning)
              return View("InProgress");
          else if (_resutsAreReady)
              return View("Results", results);
          else            
              // start the calcualtion on a new thread to avoiding having very long running connection that azure will close
              System.Threading.Tasks.Task.Run(() =&gt; SlowCalculation(params));
       }
  </code></pre>
  
  <p>The security check that I show in SlowCalculation is actually berried way down in some libraries I use, so I don't really want to change that if I can help it.  I just want to get the principal from my request into my thread.</p>
  
  <p>I have tried passing the identity into the thread function, but it gets disposed when the request completes.</p>