Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of static Variable in multi-user ASP.NET web application

Tags:

c#

static

asp.net

Does static variables retain their values across user sessions?

I have a ASP.NET web application where I have two buttons. One for setting the static variable value, another for Showing the static variable value.

namespace WebApplication1 {     public partial class WebForm1 : System.Web.UI.Page {     public static int customerID;      protected void Page_Load(object sender, EventArgs e)     {      }      protected void ButtonSetCustomerID_Click(object sender, EventArgs e)     {         customerID = Convert.ToInt32(TextBox1.Text);     }      protected void ButtonGetCustomerID_Click(object sender, EventArgs e)     {         Label1.Text = Convert.ToString(customerID);     } }  } 

While this works in single-user environment, What happens if there are 2 users simultaneously logged in from two computers, User 1 sets the value as 100, then User 2 sets the value as 200. after that user 1 invokes the Get Value button. What will he see as the value?

like image 715
Manas Saha Avatar asked Jan 04 '13 09:01

Manas Saha


People also ask

What is the scope of static variable?

The scope of the static local variable will be the same as the automatic local variables, but its memory will be available throughout the program execution. When the function modifies the value of the static local variable during one function call, then it will remain the same even during the next function call.

How can we use static variable in multiple files?

A static variable cannot be used across files. Note that 'static' when applied to C variables means something entirely different from C++ or Java static member variables.

Are static variables shared between sessions?

Yes, static values will remain same for all users. if one user is updating that value, then it will be reflected to other users as well.

What is the lifetime and scope of static variable?

The space for the static variable is allocated only one time and this is used for the entirety of the program. Once this variable is declared, it exists till the program executes. So, the lifetime of a static variable is the lifetime of the program.


1 Answers

Does static variables retain their values across user sessions?

Yes, that's why you should be VERY careful when you use static variables in a web app. You will run in concurrency issues as more than one thread servicing a request can modify the value of the variable.

While this works in single-user environment, What happens if there are 2 users simultaneously logged in from two computers, User 1 sets the value as 100, then User 2 sets the value as 200. after that user 1 invokes the Get Value button. What will he see as the value?

The user will see 200 afterwards.

like image 143
Icarus Avatar answered Sep 19 '22 12:09

Icarus