Does a single web request to IIS stay on a single

2019-06-21 20:03发布

问题:

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.

回答1:

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.



回答2:

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.



回答3:

The session remains constant for the duration of the request. Why not use that?



回答4:

I would look at maybe using ELMAH and or log4net to get what you need done as it is simple to use and now even simpler to install using NuGet package manager.

http://code.google.com/p/elmah/

http://logging.apache.org/log4net/

Sometimes it's great to use code that is already tested and configured for the environment you need rather than rolling your own, but hey that's your call.



回答5:

If you are prepared to potentially lose the log data you have accumulated then you could wait until the end of the request to write to the log, irrespective of thread safety. If it's important to you that every event be logged then I would suggest that you write events to the log as they occur rather.