问:使用线程本地存储在.NET的最佳做法?线程、做法、NET

2023-09-03 07:00:47 作者:浅笑あ忆往昔

我在我的应用程序的要求,我认为可以通过使用线程本地存储来满足,但我不知道,如果它的那些东西,最好是避免的。

I have a requirement in my application that I think can be met by using thread local storage, but I'm wondering if it's one of those things that's best to avoid.

我已阅读关于这个问题的几篇文章:

I have read a few articles on the subject:

HTTP://www.dotnet$c$ crs.com/web/Articles/ShowArticle.aspx?article=58

的http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(vs.80).aspx

我知道的如何的使用它,我只是想知道,如果我的应的使用它。

I know how to use it, I'm just wondering if I should use it.

任何意见,陷阱要注意的?

Any advice, gotchas to be aware of?

下面是用例:

我漏斗通过一些方法做了很多记录每个查询的所有数据访问。有一件事我是登录命令文本与命令,从我的跟踪日志填满,所以我可以简单地复制粘贴直接到SQL Management Studio中。

I funnel all data access through a few methods that do a lot of logging about each query. One thing I log is a complete dump of the command text with commands filled in so that I can simply copy-paste from my trace logs directly into Sql Management Studio.

方式在Global.asax中我我发送电子邮件给管理员提供尽可能多的信息,我可以当我得到一个未处理的异常的Web应用程序。我想提出的SQL命令转储文本这封邮件时,我得到的SQLException,当一个页面打击,因为查询了这将节省我通过跟踪日志挖掘的时间。

Way up in global.asax in my web apps I send email to admins with as much information as I can when I get an unhandled exception. I want to put that sql command dump text into this email when I get a SqlException, which will save me the time of digging through trace logs when a page blows up because of a query.

我不想改变我的数据访问类的方法签名,这样我可以通过一些参考一路下跌的堆栈,只是把它弄出来时,我得到一个异常。我想也许TLS将是一个很好的地方放东西,如lastsqlcommand,但不看像一个可行的解决方案。

I don't want to change the method signatures of my data access classes just so I can pass some reference all the way down the stack, just to get it out when I get an exception. I was thinking maybe TLS would be a good place to put something like "lastsqlcommand", but that's not looking like a viable solution.

推荐答案

一个疑难杂症的asp.net应用:单个请求可能切换线程,即如果在同一会话并行请求的处理。正因为如此,任何事情你把TLS的HttpApplication.PostRequireRequestState事件之前可能不会有以后,因为你是在不同的线程。

A gotcha for asp.net applications: the processing of a single request might switch threads, namely if there are parallel requests in the same session. Because of this, anything you put in TLS before the HttpApplication.PostRequireRequestState event might not be there later, because you are on a different thread.

[由提问者编辑]

有关我的具体使用情况下,我最终加入一个键值对的SqlException.Data字典,然后我找回当我登录异常的详细信息。这给了我,我希望利用线程本地存储的功能。

For my particular use case, I ended up adding a key-value pair to the SqlException.Data dictionary, which I then retrieve when I log the exception details. This gives me the functionality I was hoping to use thread local storage for.