C# – Static variables in web applications

asp.netcnetsessionstatic-members

Can I use static variables in my web application ? what are the alternatives to static ? When I use static variables in pages and more than one user use the application, it makes conflict data (incorrect data).

What are the limits of using static members?

Are static members shared in memory?

Best Answer

Consider storing your shared variables in the HttpApplication object or in the Cache object.

However, if you are trying to store values for each user separately, you should store those values in a Session variable.

Static variables inside Asp.Net are shared in the memory space of the w3svc.exe process and are NOT thread-safe. They can be accessed and modified by any user of the application. This could lead to unwanted modifications, unless you write your own lock mechanism around the storage of those values.

You should try a syntax like:

Application["KEY"] = value;

to store shared application-wide data and

Session["KEY"] = value;

to store data on a per-user basis

You can use the WebCache object to store data in the web server's memory with expiration conditions. Syntax for that looks similar to:

Page.Cache.Insert("KEY", "VALUE", null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);

More on the syntax of managing the WebCache object can be found at:

http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx