Saturday, January 24, 2015

HttpContext.Current Null in Asynchronous Methods

I created a page that had some logic to dynamically create the page.  It was doing a lot of fetches from the database and then calculating how to display each batch of data that was retrieved.  The page became slow.

To speed it up I converted the most time intensive loop to a parallel for each.  Inside the loop it was using HttpContext.Current.  Once I made the loop Parallel HttpContext.Current was null inside things called inside the loop..

It appears that if you leave the main thread of execution it no longer has a reference to the current context.

I found that HttpContext.Current can be set as well as read.  Outside the parallel loop I captured HttpContext.Current in a local variable.  I then accessed the variable in the loop.  The other things I was calling inside the parallel for each needed HttpContext.Current, so I set HttpContext.Current to the local variable.  The other methods were able to read HttpContext.Current as long as they were on the same thread as the calling method.