Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a single web request to IIS stay on a single thread?

I want to write a logging http module that stores a list of log events for a single request in thread local storage while the request executes. On End_Request I want to write all the events back to persistent storage.

Question is, will one request match to one thread? I.e. can I assume from anywhere in my code that I can add items to the IEnumerable and they will properly be all together at the end of the request.

like image 986
Jonathon Kresner Avatar asked Feb 09 '11 12:02

Jonathon Kresner


2 Answers

No. ASP.NET can potentially switch threads while processing a request. This is known as thread-agility.

There are only certain points where it can/will do this. I can't remember what they are off the top of my head - searching for a reference now...

But the short answer is NO: you can't rely on the same thread-local storage being accessible for the entire duration of the request.

like image 124
LukeH Avatar answered Oct 18 '22 20:10

LukeH


You might be better off using Context.Items rather than thread storage - that's per request. You don't need to worry about what the server is doing with its threads that way.

like image 4
MrKWatkins Avatar answered Oct 18 '22 20:10

MrKWatkins