Wojna
Wojna

Reputation: 146

.net core HttpContext null inside async Task.Run

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?

Upvotes: 3

Views: 1389

Answers (1)

Paulo Morgado
Paulo Morgado

Reputation: 14836

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.

Upvotes: 2

Related Questions