views:

18

answers:

1

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?

+4  A: 

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
Thanks, it seems I worked too late yesterday. tThis is the case when I need just normal static.
Sergey Osypchuk
@Sergey, ensure proper synchronization if you are using static variables in a multi-threaded environment such as ASP.NET.
Darin Dimitrov