3

I'm using .net core 3.1 api project and i want to access HttpContext inside my Task.Run block. Here is my code:

          // before Task.Run my HttpContextAccessor.HttpContext has correct values      
Task.Run(async () =>
               {               
                   //any other method with await here
                    var data = await SomeMethod(config); // in that method HttpContextAccessor.HttpContext is null

                }, cancellationToken)

In asp.net i could use friendlysynchronizationcontext to deal with it but in .net core there is no synchronization context.

Can someone provide me a solution/explanation how to fix that problem?

3
  • Hi @Wojna, so could you please share the method you call HttpContextAccessor? How do you register HttpContextAccessor service into that method? Commented Aug 10, 2021 at 5:34
  • @Rena im using autofac so i use IHttpContextAccessor contextAccessor in my service constructor. And registered in startup builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().SingleInstance(); Commented Aug 10, 2021 at 5:42
  • API sends response before Task can use it as suggested in answer it is better to extract data from request and then use it in a seperate method. I also got bitten by the similar scenario Commented Feb 3, 2022 at 15:16

1 Answer 1

2

From the documentation:

HttpContext isn't thread-safe. Reading or writing properties of the HttpContext outside of processing a request can result in a NullReferenceException.

Capturing HttpContext or using IHttpContextAccessor to access it can get you in trouble.

The best practice is to collect whatever information is needed from the request, process it and use the result of the processing to produce the response.

Also, requests are handled on thread pool threads and Task.Run shedules work to run on a thread pool thread. That incurs in an extra threads being used, extra context switching and extra thread pool work with no real benefit (quite the contrary) to the application.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.