Jonathan Oliver
Jonathan Oliver

Reputation: 5267

Maintain a reference to HttpContext on different thread after request has completed

I've been trying to determine how safe it is to maintain a read-only reference to the HttpContext after a request has completed. Specifically, I'm looking to grab a reference to HttpContext.Current when a request is executing, and then place a reference to the context into an in-memory queue for later evaluation (possibly up to a few seconds later) on a different thread.

Obviously, trying to work with and attempting to write to the context.Response won't work and I'm not particularly interested in that. Instead, I'm interested in reading a few values on the context.Request property and a few other values from the context itself, e.g. context.Timestamp, context.Items, and maybe a few others.

Preliminary tests indicate I can do this, but I'm trying to program intentionally rather than by coincidence. Can anyone point to any documentation (or perhaps a blog post or something from Jon Skeet) that indicates that references can be maintained after the HTTP request is complete?

Upvotes: 1

Views: 598

Answers (1)

John Saunders
John Saunders

Reputation: 161773

No, this isn't safe, but it has little to do with threading.

It's HttpContext.Current. That's context as in "context of the current request".

Don't use this after the request is over!

The various IDisposable resources in the context will have been disposed of, so don't use them. Any number of other things that were valid during the request will not be valid because the request is over.

Once you decide what parts of it you need, copy those parts and save them.

Upvotes: 2

Related Questions