ASP.NET C# Static Variables Are Global

ASP.NET C# Static Variables are global?

Yes, in ASP.NET a static fields lifetime is for the app domain (note that this differs a bit for generic types).

I'd recommend using the server Session for storage of data you want to associate with an instance of a client browser session (user login).
i.e.

Session["_groupID"] = Convert.ToInt16(Request.QueryString["GroupID"]);

you can retrieve it by doing:

short groupID = Convert.ToInt16(Session["_groupID"]);

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

How to use a global variable in ASP.net without using it as a static variable.?

I think you can use a Seesion variable for that.

 Session["Key"]=value;

Create a property get and set and use in you code. As session is different for different user it will work fine.

Edit 1

 public string yourProp {
get {return Session["Key"].ToString()}
set {Session["Key"]=value}
}

Also you need to initialize or put some value on page load !ispostback so that there is no null reference error.

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.

Is it a good idea to use static variables in Asp.Net MVC?

Its tricky to say anything here. Static in itself do not have problem. It depends on how you are using it. As you said you are putting some global counter in variable. So multiple threads will modify it; right? Make sure this call is thread-safe. Otherwise the counters will be wrong.

If this was some rarely written and mostly read-only value, it was not an issue at all.

If this is a value known to you at design time, better you use const.

You should also consider IIS recycles application pool. In that case, new Application instance will be created and two copies of your static variable will exist.

If this all does not create problem for you then static is ok.

Where does static variable work in ASP.NET page?

Unless it's [ThreadStatic], a static variable will only have one value for each AppDomain.

In ASP.Net, each application has its own AppDomain, so static variables will be shared by all requests in the application. This is what the interviewer was getting at – using static variables in ASP.Net applications is a common mistake that can lead to mysterious corruption errors when multiple requests happen at once.

Global.asax.cs and Static variable

You could use an application variable:

public static IList<MyData> Data {
get
{
if (Application["MyIListData"] != null)
return (IList<MyData>)Application["MyIListData"];
else
return new IList<MyData>();
}
set
{
Application["MyIListData"] = value;
}
}

protected void Application_Start(object sender, EventArgs e)
{
Data = Load();
}

Not really much different in actual implementation except that now it's available globally through that variable name as an application variable.

Static variable Behaviour in Asp.Net

So want to know the behavior of the static variable in Asp.Net with
C#.

are static variable equal to global variable which is accessible to
all user? If it is set by user A to true can user B get that value as
True or it has different instance of the variable.

The behavior is like that only if your run your site under one working process on your pool.

If your pool have more than one working process, then each process have their static values, and is unknown to you what process is given to each request, to each user. And process together they are not communicate.

So let say that you have a pool with 4 working process.

UserA ask for a page, Process 1 is replay and set a static value to A.

UserB ask for a page, Process 1 is replay and the static value is A.

UserA ask for a page, Process 2 is replay and the static value is not set.

and so on.
More on the subject:
Lifetime of ASP.NET Static Variable

Where are static variables stored in asp.net aspx page

Using static variables instead of Application state in ASP.NET

Static methods on ASP.NET web sites

Asp.net static object appears sometimes as non global

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.



Related Topics



Leave a reply



Submit