Lifetime of ASP.NET Static Variable

Static variables persist for the life of the app domain. So the two things that will cause your static variables to ‘reset’ is an app domain restart or the use of a new class. In your case with static variables stored in an aspx Page class, you may be losing the static variables when ASP.NET decides to recompile the aspx Page into a new class, replacing the old page class with the new one.

For those reasons if the system decide to restart or replace the class (.NET doesn’t kill or unload classes/assemblies in a running app domain) then your static variables will reset because you are getting a new class with the restart or replacement. This applies to both aspx Pages and classes in the App_Code folder

ASP.NET will replace a class if for any reason thinks that need to recompile it (see ASP.NET dynamic compilation).

You can’t prevent the loss of static variables from an app domain restart, but you can try to avoid it from class replacement. You could put your static variables in a class that is not an aspx page and is not in the App_Code directory. You might want to place them on a static class somewhere in your program.

public static class GlobalVariables
{
    public static int SomeGlobalUnsecureID;
    public  static string SomeGlobalUnsecureString;
}

The static variables are per pool, that is means that if you have 2 pools that runs your asp.net site, you have 2 different static variables. (Web garden mode)

The static variables are lost if the system restarts your asp.net application with one of this way.

  1. the pool decide that need to make a recompile.
  2. You open the app_offline.htm file
  3. You make manual restart of the pool
  4. The pool is reach some limits that you have define and make restart.
  5. For any reason you restart the iis, or the pool.

This static variables are not thread safe, and you need to use the lock keyword especial if you access them from different threads.

Since an app restart will reset your statics no matter what, if you really want to persist your data, you should store the data in a database using custom classes. You can store information per-user in Session State with a database session state mode. ASP.NET Application State/Variables will not help you because they are stored in memory, not the database, so they are lost on app domain restart too.

Leave a Comment