Getting HttpContext from a BackgroundWorker Process

I have an ASP.NET site and I am doing some work refactoring code to try to remove some lengthy processes (in the order of the hour) from the actual http request, creating a BackgroundWorker and deferring the work to processing. This was normal during testing, but when I applied the logic to the real code, I found problems with accessing session variables from code running in the background working document. It seems that the passed HttpContext object has a null session, and if I ask for HttpContext.Current, I will go back.

I assume that this is because they are in a different thread and that the session and HttpContext.Current both depend on the fact that they are in the same thread. Is there a way to access the session from a background worker, or am I stuck looking for all the variables that I need from the session and putting them in a useful data structure and then returning them back to the session (if necessary)? This clearly complicates the refactoring massive if I need to do this, so I would rather not do this.

Thanks for any thoughts you may have. I am open to other suggestions on how I could do this other than the BackgroundWorker processes (which were suggested to me in another question).

+4
source share
2 answers

Iโ€™m not sure about your requirements, but you can leave using the application cache instead of a session if you do not want the lengthy process to be attached to an individual user request.

If so, I would try replacing session use with:

HttpRuntime.Cache.Set("CacheKeyName"); HttpRuntime.Cache.Get("CacheKeyName"); 
+1
source

Here's the MSDN link that sheds some light on this. Text in particular:

If an asynchronous action method calls a service that provides methods using the BeginMethod / EndMethod template, the callback method (that is, the method that is passed as the asynchronous callback parameter to the Begin method) can be executed on a thread that is not under ASP.NET control. In this case, HttpContext.Current will be null , and the application may encounter race conditions when it contacts members of the AsyncManager class, such as Parameters. To make sure that you have access to an instance of HttpContext.Current and to avoid the race condition, you can restore HttpContext.Current by calling Sync () from the callback method .

+1
source

All Articles