I’ve read a number of articles that in order to preserve HttpContext.Current in versions prior to 4.5, we should pass on handling thread’s SynchornizationContext.
Here is a code I am attempting to execute:
TaskScheduler taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() => HandleInquiry(currentInquiry, request),
CancellationToken.None,
TaskCreationOptions.None,
taskScheduler)
When I debug through this code, I can confirm that the taskScheduler contains AspNetSynchronizationContext prior to Task scheduling. However, inside the HandleInquiry method (inside a Task) the SynchronizationContext.Current is null and HttpContext.Current is also null. I am sure I am missing something obvious.
It’s a bad design to access HttpContext in background tasks. The proper way is to pass only the needed information as parameters. But if you are relying on some legacy and badly written code that you cannot modify at this stage you could pass the entire HttpContext as parameter and reassign it inside the task: