Using Static Variables Instead of Application State in ASP.NET

Using static variables instead of Application state in ASP.NET

What Microsoft says

ASP.NET includes application state primarily for compatibility with
classic ASP so that it is easier to migrate existing applications to
ASP.NET. It is recommended that you store data in static members of
the application class instead of in the Application object. This
increases performance because you can access a static variable faster
than you can access an item in the Application dictionary.

reference : http://support.microsoft.com/default.aspx?scid=kb;en-us;Q312607

My experience

The main different between static variables and Application state, is that the Application state is the same across all threads and pools, but the static is the same only per pool.

After new tests I see that the Application state variables are the same as static variables, and they just reference to a static variable on the application, and they just exist for compatibility reasons as Microsoft says

If you have 4 pools running your site (web garden) then you have 4 sets of different static memory.

Your code

About your code, you have bug for the way you try to access your dictionary data, and you will going to have errors in real web. This part of the code is lock the variable of the full Dictionary but not lock the change you going to make when you use it.

// this is not enough to manipulate your data !
public static Dictionary<string, object> CacheItems
{
get { lock (locker) { return cacheItems; } }
set { lock (locker) { cacheItems = value; } }
}

The correct approach is to lock all actions of add/remove until you done, for example.

private static Dictionary<string, object> cacheItems = new Dictionary<string, object>();
private static object locker = new object();
public Dictionary<string, object> CacheItems
{
get{ return cacheItems; }
set{ cacheItems = value; }
}

SomeFunction()
{
...
lock(locker)
{
CacheItems["VariableName"] = SomeObject;
}
...
}

From the other hand when you manipulate data on application state you need to use the global lock of it Application.Lock(); and Application.UnLock(); for example

Application.Lock();
Application["PageRequestCount"] = ((int)Application["PageRequestCount"]) + 1;
Application.UnLock();

To close with some conclusion:

Avoid Application state and just use static variables on your code.

What is better: Static variable V.S. Asp.NET Application Session?

If you only have one of those, there is little difference.

If you have several, you should use static variables rather than Application variables. The Application.Lock method will lock all Application variables, while you can use separate syncronisition identifiers for your static variables, so that each lock only affects the code that accesses that specific variable.

ASP.NET Application state vs a Static object

From: http://support.microsoft.com/default.aspx?scid=kb;en-us;Q312607

ASP.NET includes application state
primarily for compatibility with
classic ASP so that it is easier to
migrate existing applications to
ASP.NET. It is recommended that you
store data in static members of the
application class instead of in the
Application object. This increases
performance because you can access a
static variable faster than you can
access an item in the Application
dictionary.

Also, yes, static variables behave the same way regardless of where they are loaded from, and exist exactly once per app domain (unless you're talking about those labeled [ThreadStatic])

static variables in asp.net/C#

Personally I try to avoid static variables as much as possible. They make the code difficult to unit test and also could introduce subtle bugs due to concurrent access and race conditions.

As far as your requirement is concerned you could use store the variable as a property of the control in the ViewState. If it is user specific data that you are trying to store then you could use the Session state.

Use static global variable class in ASP.NET MVC web application

To answer your question as to whether it is 'okay' to do this, I think that comes down to you.

I think the biggest thing to know is when that data is going to get refreshed. From experience I believe that static information gets stored in the application pool, so if it is restarted then the information will be refreshed.

Lifetime of ASP.NET Static Variable

Consider how many times you need that information, if you only need it once at startup, is it worth having it as a static. If you are getting that information a lot (and say for example it is stored in a database) then it may be sensible to store that in a cache somewhere such as a static member.

I think my only recommendation with static member variables is asp is keep them simple, booleans seem fine to me. Remember that users do share the same application meaning that static variables are global for all users. If you want a user specific variable then you want to use sessions cache.

Always remember the two hardest thing in programming

  1. Naming things
  2. Cache invalidation
  3. Off by one errors

https://martinfowler.com/bliki/TwoHardThings.html

Even though this is a joke, it holds a lot of truth

Hope this helps

Using static lists vs static variables in ASP.NET

"Per-user" information should be stored in Session state or custom storage that allows to pick data based on user identity.

Note that caching large amount of data in session state may actually decrease performance is it consumes too much space (in-memory state) or need to be serialized on each request for out-of-process sessions state like SQL/state server.

Static fields are always shared across all requests in the same application (on same machine for multi-server cases). As such they should be used to store static data that does not depend on user identity like list of countries/states. Additionally since it is shared across all requests it may require synchronization (i.e. using lock) if data structure is mutable (i.e. you can add more countries to list/dictionary).

It is often better to use .Net in Cache class instead static variables as it allows automatic expiration/refreshing of data and let you unload unused objects from memory.

Session State SQLServer deleting static variables in asp.net

This was very wrong. A static class member is shared by all threads in the process. You called dbc.StoredProcedureTOReturnTabsNames multiple times for different users possibly at the same time (in parallel threads), [re]assigning listLbl and listHead multiple times.

Do the contents of listLbl and listHead depend on CheckUser.user_id and CheckUser.user_access? Are these two another pair of static's?

using static Dictionary instead of session asp.net mvc

Yes, you can change the static variables in the site, But You need to use this to change the data but that is not enough you need to lock this data until you have done.

public static Dictionary<string, object> CacheItems
{
get{ return cacheItems; }
set{ cacheItems= value; }
}

How to Lock?

The approach you need to use to lock all actions of add or remove until you done is:

private static Dictionary<string, object> cacheItems = new Dictionary<string, object>();
private static object locker = new object();
public Dictionary<string, object> CacheItems
{
get{ return cacheItems; }
set{ cacheItems = value;}
}

YourFunction()
{
lock(locker)
{
CacheItems["VariableName"] = SomeObject;
}
}

for manipulating the data on application state you need to use the global lock of it Application.Lock(); and Application.UnLock();. i.e

Application.Lock();
Application["PageRequestCount"] = ((int)Application["PageRequestCount"])+1;
Application.UnLock();

Last: Avoid Application State and use the Static Variable to Manage the Data across the Application for Faster Performance

Note: you can add one lock at the time only so remove it before you are trying to change it

Keep in Mind : The static variables will be shared between requests. Moreover they will be initialized when application starts, so if the AppDomain, thus application gets restarted, their values will be reinitialized.

Static variables in asp.net?

Yes, there can be conflicts. You can end up with a lot of unexpected behaviors. Avoid them as you may have concurrency issues.



Related Topics



Leave a reply



Submit