ThreadStatic 成员在每次页面加载时都会失去价值
我在 asp.net Web 应用程序中有 veeeeryyy 基本单例:
[ThreadStatic]
private static BackgroundProcessManager2 _Instance;
public static BackgroundProcessManager2 Instance
{
get
{
if (_Instance == null) // **
{
_Instance = new BackgroundProcessManager2();
}
return _Instance;
}
}
通常一切都很好,但这次在每个页面加载 _Instance 为空。
此外,当我尝试在标记为 ** 的行中观看 _Instance 时,我遇到了非常奇怪的错误:
无法获取字段“_Instance”的值,因为有关包含类的信息不可用。
什么可以导致此类上传?
I have veeeeryyy basic singleton in asp.net web application:
[ThreadStatic]
private static BackgroundProcessManager2 _Instance;
public static BackgroundProcessManager2 Instance
{
get
{
if (_Instance == null) // **
{
_Instance = new BackgroundProcessManager2();
}
return _Instance;
}
}
And ussually everything is fine, but this time on every page load _Instance is null.
Additionally, i have very strange error when trying to watch _Instance in line marked **:
Cannot fetch the value of field '_Instance' because information about the containing class is unavailable.
What can couse this class to upload?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ThreadStatic 意味着该变量绑定到给定的托管线程。 ASP.NET 使用线程池来服务用户请求。这意味着每个页面可能由不同的线程提供服务,因此您的实例变量为 null,因为每个请求都是由池中的不同线程提供服务,但这是随机的并且取决于许多因素。
另请注意,用户请求不必与工作线程绑定。例如,如果您使用异步页面,则页面可以在给定线程上开始处理并在另一个线程上完成。这就是原因之一为什么
ThreadStaticHttpContext
,因为它始终与用户请求相关并且与线程无关。ThreadStatic
means that the variable is tied to a given managed thread. ASP.NET uses a pool of threads to service user requests. This means that each page might be served from a different thread, so your instance variable is null as each request is serviced from a different thread from the pool but this is random and will depend on many factors.Also note that a user request is not necessary tied to a worker thread. For example if you are using asynchronous pages the page could start processing on a given thread and finish on another. That's one of the reasons why
ThreadStatic
should be avoided in ASP.NET applications whereHttpContext
should be preferred as it is always tied to a user request and is thread agnostic.