Does a single web request to IIS stay on a single

2019-06-21 20:07发布

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.

5条回答
ゆ 、 Hurt°
2楼-- · 2019-06-21 20:32

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.

查看更多
家丑人穷心不美
3楼-- · 2019-06-21 20:35

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.

查看更多
放荡不羁爱自由
4楼-- · 2019-06-21 20:38

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.

查看更多
三岁会撩人
5楼-- · 2019-06-21 20:38

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.

查看更多
Root(大扎)
6楼-- · 2019-06-21 20:46

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

查看更多
登录 后发表回答