0

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?

st78
  • 8,028
  • 11
  • 49
  • 68

1 Answers1

4

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks, it seems I worked too late yesterday. tThis is the case when I need just normal static. – st78 Aug 20 '10 at 13:43
  • @Sergey, ensure proper synchronization if you are using static variables in a multi-threaded environment such as ASP.NET. – Darin Dimitrov Aug 20 '10 at 13:46
  • @DarinDimitrov, I get exactly the same message when debugging in VS one of my applications: instanceLock Cannot fetch the value of field 'instanceLock' because information about the containing class is unavailable. object. It seems that there are cross-references between the static fields of several classes and this causes the construction of their instances not to be completed. Could you, please, briefly describe a strategy to avoid this happening? If you prefer to contact me personally: dnovatchev at gmail dot com . Thanks a lot in advance for your time. Blagodaria ti, Darine. – Dimitre Novatchev Aug 18 '14 at 17:56
  • @DarinDimitrov, Please, ignore my previous comment. I found out that this was an issue with VS2013, installing the latest VS2013 Update fixed the issue. – Dimitre Novatchev Aug 19 '14 at 14:07