Threading & Lost HttpContext

On my site I need to do some CPU-heavy computing once a day. Specifically, I calculate the ADP (Average Draft Position) for each player in my database. The way I currently do this is by time-stamping each ADP calculation, then each time a cheat sheet is opened by a user I check to see if it has been at least a day since the last calculation. If it has been more than 24 hours, I kick-off a new Thread where the ADP calculation occurs and return the user to their sheet.

I contemplated doing the ADP Calculation in a Stored Procedure which could be kicked-off via a Trigger, but the code seemed way too complex to perform there so I opted for C# code. Also, a new Thread seemed to make the most sense because it could potentially take a 30 seconds to a minute (and even longer) to do the calcuations, but I don’t want the user to have to wait for this to complete.

While the ADP calculation seems to work, at some point post-processing I’m losing the HttpContext reference in my BLL. Although the ADP calculation works, an exception always seems to get thrown the next time the HttpContext gets referenced in my BLL.

Any ideas?

HttpContext is null unless instantiated by asp.net. You shouldn’t reference HttpContext in the BLL at all. If it’s really necessary , pass it as a dependency .

I perform caching of my business objects in my BLL and ‘Cache’ is stored in the HttpContext (i.e. HttpContext.Current.Cache). It has always worked flawlessly until I introduced threading. I’m guessing that it has something to do with the fact that the user is being returned to the page immediately while the new Thread no longer has context because the Http Request has completed.

Maybe I should just ensure that my ADP calculation code does not utilize Cache in any way since the HttpContext is gone.

Maybe I should just ensure that my ADP calculation code does not utilize Cache in any way since the HttpContext is gone.

Yep…

We had some similar stuff to solve, trick was to stand up a web service for our external app to manage the public-facing site’s cache. Worked brilliantly.