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