Lifetime of static variable in IIS

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.

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.

Best Practice
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 inSession 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.

No Comments

Post a Comment