title: Why is System.Web.HttpContext.Current null after awaiting an async method in a controller action?
body: <p>In my ASP.NET MVC web application, one of my <code>Controller</code> action methods invokes some code that relies on getting information from the current <code>HttpContext</code>. That code is not part of my <code>Controller</code>, so it can't use <code>Controller.HttpContext</code> - instead it uses <code>System.Web.HttpContext.Current</code>. (I know that's a bad idea, but I'm not in a position to change that).</p>
  <p>This was all working until I added an <code>await</code> to my <code>Controller</code> action method. Now, when I subsequently invoke the code that uses <code>System.Web.HttpContext.Current</code> it fails because <code>HttpContext.Current</code> is <code>null</code>.</p>
  <p>I did some reading and found something that said that <code>System.Web.HttpContext.Current</code> is only set on a the thread that's processing a web request. That makes sense. However, I'm surprised that simply using <code>await</code> is enough to switch to a different thread.</p>
  <p>My understanding is that using <code>await</code> without <code>ConfigureAwait(false)</code> (as in <code>var result = await myTask;</code>) ensures that the code following the <code>await</code> is invoked using the <code>SynchronizationContext</code> in effect prior to the <code>await</code>.</p>
  <p>I mentally equated this with &quot;running on the same thread&quot; - that is, the code after the <code>await</code> would run on the same thread as the code before the <code>await</code> (even though the <code>Task</code> being awaited might be executed on a different thread). Turns out that's not true - the <code>Thread.CurrentThread.ManagedThreadId</code> is different before and after the <code>await</code>.</p>
  <p>Oddly, the behaviour I'm seeing is the <em>opposite</em> of what's described in <a href="https://stackoverflow.com/questions/55080787/why-httpcontext-current-is-not-null-in-async-await-with-configureawait">this question</a>.</p>
  <p>I'm confused - can anyone shed any light on whether (a) I should expect <code>System.Web.HttpContext.Current</code> to be null after any <code>await</code> call, and (b) whether there's any way to make the code after the <code>await</code> resume on the same thread so that it's <em>not</em> null?</p>