ThreadStatic 成员在每次页面加载时都会失去价值

发布于 2024-09-14 21:30:04 字数 543 浏览 5 评论 0原文

我在 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 技术交流群。

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

发布评论

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

评论(1

成熟的代价 2024-09-21 21:30:04

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 where HttpContext should be preferred as it is always tied to a user request and is thread agnostic.

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