Friday, April 18, 2008

Life Cycle of static variables in ASP.Net

Have you ever wondered about the scope and life time of static (Shared in VB.Net) variables in ASP.Net?
- Do they get destroyed after each requests?
- Do they get destroyed after the IIS services is restarted?
- multiple apps run in the same Application Pool, do they all get the same copy (and value) of static variables?
- Does a Singleton make sense in ASP.Net

Here is what I could gather from doing some research on the web:

- static variables work in ASP.Net the same way they work in a Windows app: they are global across the whole .Net AppDomain
- each ASP.Net application gets their own AppDomain, even if they are hosted in the same application pool (same w3wp.exe or aspnet_wp.exe)
- so even if you have multiple ASP.Net applications per Application Pool, they would still get their own AppDomains, and thus the singletons/shared variables would be isolated from each other

Some people encourage initializing the singletons/static variables in the Application_Startup event, just to make sure that all the ASP.Net infrastructure.

Here are some supporting links:

http://weblogs.asp.net/jeff/archive/2007/09/21/how-do-you-get-a-true-singleton-in-an-asp-net-app.aspx

http://www.odetocode.com/Articles/305.aspx

http://blogs.msdn.com/david.wang/archive/2005/09/01/HOWTO-Provision-ASP-dotNet-AppDomains-and-IIS6-Application-Pools.aspx

http://www.vzyl.co.za/post/2008/04/Singleton-Design-Pattern-amp3b-Lifetime-of-a-static-variable-in-ASPNET-20.aspx

http://www.yoda.arachsys.com/csharp/singleton.html

1 comment:

Amanda Young said...

yes, thinking about the Life Cycle of Static variables has been keeping me up all hours.....