Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is HttpContextAccessor Thread Safe?

Tags:

There are two normal ways to access the user's HttpContext, via:

  • IHttpContextAccessor (and HttpContextAccessor) that are injected for services as so: httpContextAccessor.HttpContext
  • Or through the controller's property as so: this.HttpContext

In my code base, we make use of both cases. For the usage of HttpContextAccessor, we have them mostly in common singleton services that are shared for every request (such as logging, session handling, etc). I think this should be thread-safe as HttpContextAccessor should know how to handle it, but I see this tweet that throws me off: https://twitter.com/davidfowl/status/907248318538903553

So far it looks okay, but is there any confirmation that it is thread-safe?

like image 453
someDeveloperHere Avatar asked Oct 29 '18 14:10

someDeveloperHere


1 Answers

You're confusing two different concepts. Thread-safety is only tangentially related to HTTP requests as an HTTP request requires the use of a thread. That's pretty much it, though. HttpContext is request-scoped, so within the context of a single request, you will not have bleed-over, assuming you stay on just one thread or all operating threads run within the context of that particular request.

Where things get wonky is when you start firing off threads that run in the background, i.e. outside the request pipeline. In such situations, HttpContext may or may not exist, or it could be different for the background thread than the original thread. That's where the thread-unsafety comes in.

Long and short, whether or not HttpContext is thread-safe is the wrong question to ask. Instead, you need to ask what work is being done on a thread in what context. If you're in the request pipeline, then HttpContext will effectively be thread-safe, but that would require capturing all threads you fire off, which then pretty much negates the usefulness of using multiple threads. You might as well just do all the work on the original thread. Handling a web request is not the same as something like a desktop or mobile app. In the latter, you need to keep the main or UI thread free, so spinning off threads is a must. The web doesn't work that way; all threads are transient, serving a particular request and then returning to the pool.

like image 174
Chris Pratt Avatar answered Nov 09 '22 13:11

Chris Pratt