ASP.NET 中的 ThreadStaticAttribute

发布于 2024-10-13 21:44:46 字数 503 浏览 3 评论 0原文

我有一个组件需要为每个线程存储静态值。它是一个通用组件,可以在许多场景中使用,而不仅仅是在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

给妤﹃绝世温柔 2024-10-20 21:44:46

不,斯科特是对的:请求绝对不必在整个持续时间内在单个线程上运行。在这方面,ASP.NET 是线程敏捷的。只有少数几个点可以发生切换,但它肯定可能发生。 (我已经亲自测试过。)

您可能希望阅读此博客发布此 Spring 论坛主题了解更多信息细节。

基本上你应该找到一种不同的方式来捕获上下文。从您的角度来看,相关内容可能位于博客文章的末尾:

这是一个主要的 PITA,因为据我所知,它意味着 ASP.Net 中“ThreadStatic”式行为的唯一持久性选项是使用 HttpContext。因此,对于您的业务对象,要么您陷入 if(HttpContext.Current!=null) 和 System.Web 引用(恶心),要么您必须为静态持久性提出某种提供程序模型,在访问任何这些单例之前需要进行设置。双讨厌。

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:

This is a major PITA, because as far as I can see it mean the only persistence option for 'ThreadStatic'esque behavior in ASP.Net is to use HttpContext. So for your business objects, either you're stuck with the if(HttpContext.Current!=null) and the System.Web reference (yuck) or you've got to come up with some kind of provider model for your static persistence, which will need setting up prior to the point that any of these singletons are accessed. Double yuck.

胡大本事 2024-10-20 21:44:46

我不确定在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文