ASP.NET 中的 ThreadStaticAttribute
我有一个组件需要为每个线程存储静态值。它是一个通用组件,可以在许多场景中使用,而不仅仅是在 ASP.NET 中。
我正在考虑使用 [ThreadStatic]
属性来实现我的目标。假设它在 ASP.NET 场景中也能正常工作,因为我假设每个请求都在自己的线程中调用。
经过一番研究,我发现 Scott Hanselman 的 这篇博客文章 说使用 [ThreadStatic]
在 ASP.NET 中。
然而,大多数评论(在帖子下方)并不同意 Scott 所写的观点,他们说请求总是在一个线程中运行,并且该线程不会同时被另一个请求使用。我也是这么认为的,但很想听听这里的专家们的意见。
I have a component that needs to store static
values fore each thread. It's a general component that can be used in many scenarios and not only in ASP.NET.
I was thinking to use the [ThreadStatic]
attribute to achieve my goal. Supposing that it would also work fine in ASP.NET scenarios, because i was assuming that every Request is called in a own thread.
After some research i found this Blog Post from Scott Hanselman saying to be careful when using [ThreadStatic]
in ASP.NET.
However most of the comments (below the Post) do not agree with that was Scott wrote, saying that a Request always run in one thread and that the thread is not used by another request at the same time. That's also what I believe but would love to have some opinion about you experts in here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,斯科特是对的:请求绝对不必在整个持续时间内在单个线程上运行。在这方面,ASP.NET 是线程敏捷的。只有少数几个点可以发生切换,但它肯定可能发生。 (我已经亲自测试过。)
您可能希望阅读此博客发布和此 Spring 论坛主题了解更多信息细节。
基本上你应该找到一种不同的方式来捕获上下文。从您的角度来看,相关内容可能位于博客文章的末尾:
Nope, Scott is right: a request definitely doesn't have to run on a single thread for its entire duration. ASP.NET is thread-agile in that respect. There are only a few points where the switch can happen, but it definitely can happen. (I've tested it for myself.)
You may wish to read this blog post and this Spring forum thread for some more details.
Basically you should find a different way of capturing context. The relevant bit from your point of view is probably at the end of the blog post:
我不确定在 ASP.NET 环境中使用线程本地数据,但 .NET 4.0 附带 ThreadLocal 类。
I'm not sure about using thread local data in ASP.NET environment, but .NET 4.0 comes with ThreadLocal class.