473,726 Members | 2,262 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Trying to understand static and when to use it?

I used the following class and .aspx code below to understand how static
works on variables and methods taken from
"http://msdn.microsoft. com/library/default.asp?url =/library/en-us/csref/html/vclrfstaticpg.a sp".

I opened up two instances of my browser to simulate two users accessing the
page at the same time by pointing to Employee.aspx below. Refreshing several
times, the counter value is increased and shared between both browser
instances.

If shared variables are shared between two instances of the app running in
two browsers, My question is what happens when a static method, that accepts
parameters, is called at the same time by two users. Are the parameter
values going to be isolated from each other? What about variable declared and
used within the static method itself? I'm trying to determine what are valid
rules for making a method static or things I need to be aware of when doing
so.

My code:

using System;

namespace StaticExample
{
/// <summary>
/// Summary description for Employee.
/// </summary>

public class Employee
{
public string id;
public string name;

public Employee ()
{
}

public Employee (string name, string id)
{
this.name = name;
this.id = id;

AddEmployee();
}

public static int employeeCounter ;

public static int AddEmployee()
{
return ++employeeCount er;
}
}
}

The Employee.aspx page calls the above...

private void Page_Load(objec t sender, System.EventArg s e)
{
// Put user code to initialize the page here
Employee employee;
employee = new Employee("Test User", "1");
Response.Write( Employee.employ eeCounter);
}
Nov 17 '05 #1
4 1867
Dave,

In this case, you will want to place a lock statement around the
statement:

++employeeCount er;

The reason for this is that pages in ASP.NET are processed on different
threads. Because of this, you will need to protect the variable.

Static values are stored across the application domain. In ASP.NET, you
have one application domain running per web application, not per user
accessing the application. For this reason, you need to protect these
variables.

As for when to use static variables, in ASP.NET, I would use them when
you need to store application-wide information. It is even more important
in ASP.NET to make sure that the variable is protected for multithreaded
access (since pages are all going to be processed on different threads).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Dave" <Da**@discussio ns.microsoft.co m> wrote in message
news:3A******** *************** ***********@mic rosoft.com...
I used the following class and .aspx code below to understand how static
works on variables and methods taken from
"http://msdn.microsoft. com/library/default.asp?url =/library/en-us/csref/html/vclrfstaticpg.a sp".

I opened up two instances of my browser to simulate two users accessing
the
page at the same time by pointing to Employee.aspx below. Refreshing
several
times, the counter value is increased and shared between both browser
instances.

If shared variables are shared between two instances of the app running in
two browsers, My question is what happens when a static method, that
accepts
parameters, is called at the same time by two users. Are the parameter
values going to be isolated from each other? What about variable declared
and
used within the static method itself? I'm trying to determine what are
valid
rules for making a method static or things I need to be aware of when
doing
so.

My code:

using System;

namespace StaticExample
{
/// <summary>
/// Summary description for Employee.
/// </summary>

public class Employee
{
public string id;
public string name;

public Employee ()
{
}

public Employee (string name, string id)
{
this.name = name;
this.id = id;

AddEmployee();
}

public static int employeeCounter ;

public static int AddEmployee()
{
return ++employeeCount er;
}
}
}

The Employee.aspx page calls the above...

private void Page_Load(objec t sender, System.EventArg s e)
{
// Put user code to initialize the page here
Employee employee;
employee = new Employee("Test User", "1");
Response.Write( Employee.employ eeCounter);
}

Nov 17 '05 #2
Nicholas,

Thanks for the reply. To futher clarify an example of the method is:

A static method that accepts a ticker symbol as a string and makes and
HttpWebRequest to a url that returns a company description and stock prices
as Xml. Within this method, I then parse the XML and return only the filings
from the the method.

Just to clarify, what if two users call this at the same time? Since the
method is static, is any data within this method (parameters passed in and
local variables declared within the method) also considered static and shared
for all users of the class?

From what you are saying, I'm not sure when static would be a benefit to use
in ASP.NET.

"Nicholas Paldino [.NET/C# MVP]" wrote:
Dave,

In this case, you will want to place a lock statement around the
statement:

++employeeCount er;

The reason for this is that pages in ASP.NET are processed on different
threads. Because of this, you will need to protect the variable.

Static values are stored across the application domain. In ASP.NET, you
have one application domain running per web application, not per user
accessing the application. For this reason, you need to protect these
variables.

As for when to use static variables, in ASP.NET, I would use them when
you need to store application-wide information. It is even more important
in ASP.NET to make sure that the variable is protected for multithreaded
access (since pages are all going to be processed on different threads).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Dave" <Da**@discussio ns.microsoft.co m> wrote in message
news:3A******** *************** ***********@mic rosoft.com...
I used the following class and .aspx code below to understand how static
works on variables and methods taken from
"http://msdn.microsoft. com/library/default.asp?url =/library/en-us/csref/html/vclrfstaticpg.a sp".

I opened up two instances of my browser to simulate two users accessing
the
page at the same time by pointing to Employee.aspx below. Refreshing
several
times, the counter value is increased and shared between both browser
instances.

If shared variables are shared between two instances of the app running in
two browsers, My question is what happens when a static method, that
accepts
parameters, is called at the same time by two users. Are the parameter
values going to be isolated from each other? What about variable declared
and
used within the static method itself? I'm trying to determine what are
valid
rules for making a method static or things I need to be aware of when
doing
so.

My code:

using System;

namespace StaticExample
{
/// <summary>
/// Summary description for Employee.
/// </summary>

public class Employee
{
public string id;
public string name;

public Employee ()
{
}

public Employee (string name, string id)
{
this.name = name;
this.id = id;

AddEmployee();
}

public static int employeeCounter ;

public static int AddEmployee()
{
return ++employeeCount er;
}
}
}

The Employee.aspx page calls the above...

private void Page_Load(objec t sender, System.EventArg s e)
{
// Put user code to initialize the page here
Employee employee;
employee = new Employee("Test User", "1");
Response.Write( Employee.employ eeCounter);
}


Nov 17 '05 #3
Dave,

In this case, if your method is not accessing other static variables,
and is only working with references/values that are stored on the stack (in
other words, declared in the function), then you should have nothng to worry
about. The only thing you have to worry about at this point is other
resources you might be accessing (for example, the same file, if you are
working with files).

As for the use of static, this sounds like a good one. It doesn't sound
like it needs any kind of specialization which would require individual
instances.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Dave" <Da**@discussio ns.microsoft.co m> wrote in message
news:5E******** *************** ***********@mic rosoft.com...
Nicholas,

Thanks for the reply. To futher clarify an example of the method is:

A static method that accepts a ticker symbol as a string and makes and
HttpWebRequest to a url that returns a company description and stock
prices
as Xml. Within this method, I then parse the XML and return only the
filings
from the the method.

Just to clarify, what if two users call this at the same time? Since the
method is static, is any data within this method (parameters passed in and
local variables declared within the method) also considered static and
shared
for all users of the class?

From what you are saying, I'm not sure when static would be a benefit to
use
in ASP.NET.

"Nicholas Paldino [.NET/C# MVP]" wrote:
Dave,

In this case, you will want to place a lock statement around the
statement:

++employeeCount er;

The reason for this is that pages in ASP.NET are processed on
different
threads. Because of this, you will need to protect the variable.

Static values are stored across the application domain. In ASP.NET,
you
have one application domain running per web application, not per user
accessing the application. For this reason, you need to protect these
variables.

As for when to use static variables, in ASP.NET, I would use them
when
you need to store application-wide information. It is even more
important
in ASP.NET to make sure that the variable is protected for multithreaded
access (since pages are all going to be processed on different threads).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Dave" <Da**@discussio ns.microsoft.co m> wrote in message
news:3A******** *************** ***********@mic rosoft.com...
>I used the following class and .aspx code below to understand how static
> works on variables and methods taken from
> "http://msdn.microsoft. com/library/default.asp?url =/library/en-us/csref/html/vclrfstaticpg.a sp".
>
> I opened up two instances of my browser to simulate two users accessing
> the
> page at the same time by pointing to Employee.aspx below. Refreshing
> several
> times, the counter value is increased and shared between both browser
> instances.
>
> If shared variables are shared between two instances of the app running
> in
> two browsers, My question is what happens when a static method, that
> accepts
> parameters, is called at the same time by two users. Are the parameter
> values going to be isolated from each other? What about variable
> declared
> and
> used within the static method itself? I'm trying to determine what are
> valid
> rules for making a method static or things I need to be aware of when
> doing
> so.
>
> My code:
>
> using System;
>
> namespace StaticExample
> {
> /// <summary>
> /// Summary description for Employee.
> /// </summary>
>
> public class Employee
> {
> public string id;
> public string name;
>
> public Employee ()
> {
> }
>
> public Employee (string name, string id)
> {
> this.name = name;
> this.id = id;
>
> AddEmployee();
> }
>
> public static int employeeCounter ;
>
> public static int AddEmployee()
> {
> return ++employeeCount er;
> }
> }
> }
>
> The Employee.aspx page calls the above...
>
> private void Page_Load(objec t sender, System.EventArg s e)
> {
> // Put user code to initialize the page here
> Employee employee;
> employee = new Employee("Test User", "1");
> Response.Write( Employee.employ eeCounter);
> }


Nov 17 '05 #4
Nicholas,

Thanks! One last thing. By converting other methods similar to this over to
static, what does one really gain besides less code in that I don't have to
create instances of each class? I'm guessing static uses less resources and
helps performance in the long run.

Dave.

"Nicholas Paldino [.NET/C# MVP]" wrote:
Dave,

In this case, if your method is not accessing other static variables,
and is only working with references/values that are stored on the stack (in
other words, declared in the function), then you should have nothng to worry
about. The only thing you have to worry about at this point is other
resources you might be accessing (for example, the same file, if you are
working with files).

As for the use of static, this sounds like a good one. It doesn't sound
like it needs any kind of specialization which would require individual
instances.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Dave" <Da**@discussio ns.microsoft.co m> wrote in message
news:5E******** *************** ***********@mic rosoft.com...
Nicholas,

Thanks for the reply. To futher clarify an example of the method is:

A static method that accepts a ticker symbol as a string and makes and
HttpWebRequest to a url that returns a company description and stock
prices
as Xml. Within this method, I then parse the XML and return only the
filings
from the the method.

Just to clarify, what if two users call this at the same time? Since the
method is static, is any data within this method (parameters passed in and
local variables declared within the method) also considered static and
shared
for all users of the class?

From what you are saying, I'm not sure when static would be a benefit to
use
in ASP.NET.

"Nicholas Paldino [.NET/C# MVP]" wrote:
Dave,

In this case, you will want to place a lock statement around the
statement:

++employeeCount er;

The reason for this is that pages in ASP.NET are processed on
different
threads. Because of this, you will need to protect the variable.

Static values are stored across the application domain. In ASP.NET,
you
have one application domain running per web application, not per user
accessing the application. For this reason, you need to protect these
variables.

As for when to use static variables, in ASP.NET, I would use them
when
you need to store application-wide information. It is even more
important
in ASP.NET to make sure that the variable is protected for multithreaded
access (since pages are all going to be processed on different threads).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Dave" <Da**@discussio ns.microsoft.co m> wrote in message
news:3A******** *************** ***********@mic rosoft.com...
>I used the following class and .aspx code below to understand how static
> works on variables and methods taken from
> "http://msdn.microsoft. com/library/default.asp?url =/library/en-us/csref/html/vclrfstaticpg.a sp".
>
> I opened up two instances of my browser to simulate two users accessing
> the
> page at the same time by pointing to Employee.aspx below. Refreshing
> several
> times, the counter value is increased and shared between both browser
> instances.
>
> If shared variables are shared between two instances of the app running
> in
> two browsers, My question is what happens when a static method, that
> accepts
> parameters, is called at the same time by two users. Are the parameter
> values going to be isolated from each other? What about variable
> declared
> and
> used within the static method itself? I'm trying to determine what are
> valid
> rules for making a method static or things I need to be aware of when
> doing
> so.
>
> My code:
>
> using System;
>
> namespace StaticExample
> {
> /// <summary>
> /// Summary description for Employee.
> /// </summary>
>
> public class Employee
> {
> public string id;
> public string name;
>
> public Employee ()
> {
> }
>
> public Employee (string name, string id)
> {
> this.name = name;
> this.id = id;
>
> AddEmployee();
> }
>
> public static int employeeCounter ;
>
> public static int AddEmployee()
> {
> return ++employeeCount er;
> }
> }
> }
>
> The Employee.aspx page calls the above...
>
> private void Page_Load(objec t sender, System.EventArg s e)
> {
> // Put user code to initialize the page here
> Employee employee;
> employee = new Employee("Test User", "1");
> Response.Write( Employee.employ eeCounter);
> }


Nov 17 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1996
by: Steven D'Aprano | last post by:
I've been doing a lot of reading about static methods in Python, and I'm not exactly sure what they are useful for or why they were introduced. Here is a typical description of them, this one from Guido: "The new descriptor API makes it possible to add static methods and class methods. Static methods are easy to describe: they behave pretty much like static methods in C++ or Java." http://www.python.org/2.2.3/descrintro.html
9
3720
by: heruti | last post by:
Hi all... I've been stumped by this for days. Bit of ASP code: (IIS) Set LocalConn = CreateObject("ADODB.Connection") LocalConn.CursorLocation = adUseClient LocalConn.CommandTimeout = 0 LocalConn.Open sConnStringSO (SQL Server 2000, irrelevant what it is, see below). LocalConn.Errors.Clear
51
2560
by: Richard Hengeveld | last post by:
Hi all, I'm trying to understand how pointers for function parameters work. As I understand it, if you got a function like: void f(int *i) { *i = 0; }
4
2237
by: Deniz Bahar | last post by:
Hello, A couple days ago my friend (OOP guy) shows me what OOP was all about in C++. This morning I figured I can do pretty much the same thing with C (by putting function pointers in structures and using Macros). I've gone pretty far but I'm running into problems because the function pointers within the structures need an extra argument (a pointer to that type of structure) so they know which data to operate on. Also, I have to...
12
3097
by: Ron Weldy | last post by:
I have a test server runinng 2003/IIS 6 with a mixture of asp and asp.net files. On my workstation I have a share set up to the folder where the web files reside. I am just doing quick and dirty asp editing (like I used to be able to do with 2K/IIS5) where I use VS.NET, open an asp file, make changes, save and refresh my browser. Problem is that I get an Access is Denied error when I try to save the file and then the file gets wiped on...
3
1724
by: Michael B. Trausch | last post by:
Hello everyone, I am having a problem with static class properties that I suspect is somewhat trivial, but I don't understand what is wrong. I am using GNU C++ on Windows, though I am (hoping) to make this program cross-platform using the wxWidgets library and not using any functionality that isn't commonly supported. Anyway, the problem is that I want to have a class that has two variables and two methods that operate on the class...
2
1633
by: BLUE | last post by:
FirstClass members: - static int counter; - SingletonClass sc = SingletonClass.Instance; Moreovere FirstClass uses a static class named SecondClass with a static property SecondClass.Description. In a normal windows application: - if in the Main method I create 2 or more instances of FirstClass, they all
0
3234
by: rbukkara | last post by:
Hi, I have got the following error while trying to add a user in the LDAP Directory. javax.naming.NameNotFoundException: ; remaining name 'uid=vassila,ou=People,dc=cs,dc=uno,dc=edu' I have given all the attributes which are needed, for the user, in the code and also the proper path where the user has to be added. Please have a look at my code CODE] // This is a class file which stores all the info required for the user
4
5414
by: spectrumdt | last post by:
Hello. I am trying to extend Python with some C code. I made a trivial "Hello World" program in C that I am trying to wrap in "boilerplate" for inclusion in a Python program. But I can't compile the C code. The C compiler cannot find the required function `Py_BuildValue'. My C code looks like this:
0
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9116
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6702
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4519
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3228
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.