Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variables in web requests

How a static public variable in a static public class behaves between web requests in a C# MVC3 web project. Those types of variables mantain there values between requests or not?

like image 796
miguelbgouveia Avatar asked May 28 '14 09:05

miguelbgouveia


People also ask

What is an example of a static variable?

The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. The static variable gets memory only once in the class area at the time of class loading.

What are static variables used for?

Static variables are used to keep track of information that relates logically to an entire class, as opposed to information that varies from instance to instance.

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 static variable in HTML?

The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.


1 Answers

To answer your question in its simplest form; yes. Anything that's static will persist:

  • Between requests
  • Across all users

They won't be shared between different instances of the same application (e.g. in a load balanced scenario) and they will lose their values when the application pool recycles.

Generally speaking, it's a bad idea to try and persist state using static variables unless you have a very specific reason to do so.

If you are considering using static variables to save user-specific data between requests, don't. Because they are shared across threads (and therefore across both requests and users), you will introduce race conditions as soon as you have more than one user.

Opt for another form of storage, such as session state, cookies or - better still - a database.

like image 114
Ant P Avatar answered Oct 27 '22 10:10

Ant P