gpt4 book ai didi

c# - ASP.NET 中的 ThreadStaticAttribute

转载 作者:IT王子 更新时间:2023-10-29 04:38:20 25 4
gpt4 key购买 nike

我有一个组件需要为每个线程存储 static 值。它是一个通用组件,可以在许多场景中使用,而不仅仅是在 ASP.NET 中。

我正在考虑使用[ThreadStatic] 属性来实现我的目标。假设它在 ASP.NET 场景中也能正常工作,因为我假设每个请求都在自己的线程中调用。

经过一些研究,我发现了 this Blog Post来自 Scott Hanselman 的说法,在 ASP.NET 中使用 [ThreadStatic] 时要小心。

然而,大多数评论(在帖子下方)不同意 Scott 所写的,说一个请求总是在一个线程中运行,并且该线程不会同时被另一个请求使用。这也是我所相信的,但很想对这里的专家们发表一些意见。

最佳答案

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

您不妨阅读this blog postthis Spring forum thread了解更多详情。

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

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.

关于c# - ASP.NET 中的 ThreadStaticAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4791208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com