Static variables in ASP .NET/VB .NET

R

RB

Hi clever people :)

I've noticed a lot of people stating not to use static variables with
ASP.NET, and, as I understand it, the reason is because the variable is
shared across user sessions - which is Very Bad (tm) for reasons I
understand!

However, does this rule apply only to global static variables, or does
it apply to procedure-level static variables.

e.g. If I have a class:
==================================================
Public Class MyPretendClass
Inherits System.Web.UI.Page
ReadOnly Property SomeProperty() As Integer
Get
Static i As Integer = -1
If i = -1 Then
i = Integer.Parse(Request.Params("MyQueryStringArgument"))
End If
Return t
End Get
End Property

' REST OF CLASS, INCLUDING USE OF SomeProperty PROPERTY
End Class
==================================================

and I output SomeProperty to an asp:Label how will it work if I have 2
users (Alice and Bob), where Alice requests the page with a query string
value of 1, and Bob then accesses the page with a value of 2.

Obviously Alice will have 1 in the label, but what value will Bob have?

Many thanks,

RB.
 
A

Aidy

Your initial statement is false. There is nothing wrong with static
variables if they fill the task at hand, be they "global" or at a procedure
level.
 
R

RB

Fair point - I retract my original statement, but leave the rest of the
question open ;-)

Cheers,

RB.
 
A

Aidy

Can't you just test to get the answer? Or can you not be bothered doing
your own homework despite it only involving typing in one function and
pressing F5? Bob will also have 1 (assuming he viewed the site in a
reasonable enough time after Alice, of course)
 
B

bruce barker

statics are statics, shared for all threads in the appdomain. public and
private only controls scope (access).


-- bruce (sqlwork.com)
 
R

RB

I actually have done a test (that's where the code comes from), and I
get the value 2 for "Bob" (where Alice and Bob are 2 seperate instances
of IE).

I posted because this wasn't the behaviour I was exactly expecting, and
I wanted to know what behaviour other people were expecting. and you
suggest that I was right not to expect this behaviour.

Therefore, does anyone know why Bob get's a different value from Alice?

Actually, thinking about it, it would have to work this way, otherwise
every post-back to the server would get the same value - even if the
query string changed - I think I'll check that behaviour next.

Cheers,

RB
 
R

RB

I tested that behaviour with a HyperLink that incremented the query
string parameter each time, and that worked (i.e. it incremented it).

Private ReadOnly Property SomeProperty()
Get
Static i As Integer = -1
If i = -1 Then
i = Integer.Parse(Request.Params("MyQueryStringArgument"))
End If
Return i
End Get
End Property


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
lblTest.Text = SomeProperty
HyperLink1.NavigateUrl =
"http://localhost/StaticTest/WebForm1.aspx?MyQueryStringArgument=" &
(SomeProperty + 1)
End Sub

Therefore, I'm assuming that procedure-level static variables persist
ONLY for the lifetime of the page (or any object I suppose) they belong
to. If someone could confirm that, I'd really appreciate it :)

Cheers,

RB.
 
R

RB

That's what I thought as well - but doing testing suggests that
procedure-level statics work differently, and exist only for the
lifetime of the page.

Ah - is that the thing then. Is it the case that if I had 2
near-simultaneous web-page requests, then the static property value
*would* be shared?
 
R

RB

AHHH - I think i know what's going on - I'm being a thicky (naturally!)

Every user has their own instantiation of the page object in question,
so the procedure level static variables *are* individual to each user,
as the procedure they are in is not shared.

Therefore, it is safe to use this technique (of caching things in a
static variable) as different users will not be able to share values.

If the above is not correct, please let me know!!

Cheers,

RB.
 
G

Guest

Perhaps, but I fail to see what advantage this could possibly give you.
Understanding that the Page class disintegrates --*Poof* and is completely
gone when it has finished and the page is sent out to the requesting browser.
Static -- within the context you are using it (in private transient scope)
accomplishes "nada".
-- Peter
Recursion: see Recursion
site: http://www.eggheadcafe.com
unBlog: http://petesbloggerama.blogspot.com
BlogMetaFinder: http://www.blogmetafinder.com
 
R

RB

Hi Peter,

The advantage is that it's an easy way of caching objects for the
duration of the page - think of it loosely like the singleton pattern.

I could do the same thing with private variables within the class of
course - I just think the static approach looks neater!

I was just a little concerned that it would not work the way I thought
it would - hence my posting...

Cheers,

RB.
 
M

Mark Rae [MVP]

The advantage is that it's an easy way of caching objects for the duration
of the page - think of it loosely like the singleton pattern.

I guess it depends on your definition of the word 'advantage' - in this
case, there's no advantage (IMO) at all, since you get no additional benefit
or functionality...
I could do the same thing with private variables within the class of
course

Indeed, which (I believe) was Peter's point...
I just think the static approach looks neater!

Well obviously that's a personal preference, and nothing wrong with that...
 
R

Rory Becker

I just think the static approach looks neater!
Well obviously that's a personal preference, and nothing wrong with
that...

In addition to "looking neater", the use of the static keyworkd makes the
var only accecible from the proc in which it's declared.

In the same way as private fields are better(safer due to being inaccessible
outside the scope of their use) compared to public fields, I would say that
proc static vars are better again, if you can get away with using them as
they prevent misuse from outside the proc.
 
M

Mark Rae [MVP]

In addition to "looking neater", the use of the static keyworkd makes the
var only accecible from the proc in which it's declared.

In C# (unlike C++), static variables can't be declared inside methods (which
I assume is what you mean by 'proc')...

E.g. this compiles:

public partial class MyClass: System.Web.UI.Page
{
static string MyString = String.Empty;

protected void Page_Load(object sender, EventArgs e)
{

}
}

but this doesn't:

public partial class MyClass: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
static string MyString = String.Empty;
}
}
 
R

Rory Becker

In C# (unlike C++), static variables can't be declared inside methods

Fair enough but the ubject of this post details that the OP was using VB.net
which does allow such.

VB used Static as a keyword for this since a long way before VB.Net which
is probably wht Shared is used to mean Static in the other sense.
 
M

Mark Rae [MVP]

Fair enough but the subject of this post details that the OP was using
VB.net which does allow such.

VB used Static as a keyword for this since a long way before VB.Net which
is probably why Shared is used to mean Static in the other sense.

Apologies - you're quite correct. According to MSDN:

[Static] Specifies that one or more declared local variables are to remain
in existence and retain their latest values after termination of the
procedure in which they are declared.

Remarks
Normally, a local variable in a procedure ceases to exist as soon as the
procedure terminates. A static variable remains in existence and retains its
most recent value. The next time your code calls the procedure, the variable
is not reinitialized, and it still holds the latest value you assigned to
it. A static variable continues to exist for the lifetime of the class or
module in which it is defined.

Rules
Declaration Context. You can use Static only on local variables. This means
the declaration context for a Static variable must be a procedure or a block
within a procedure, and it cannot be a source file, namespace, class,
structure, or module.

You cannot use Static inside a structure procedure.

Combined Modifiers. You cannot specify Static together with ReadOnly,
Shadows, or Shared in the same declaration.

Behavior
The behavior of any local variable depends on whether it is declared in a
Shared procedure. If the procedure is Shared, all its local variables are
automatically shared, including the Static variables. There is only one copy
of such a variable for the entire application. You call a Shared procedure
using the class name, not a variable pointing to an instance of the class.

If the procedure is not Shared, its local variables are instance variables,
including the Static variables. There is an independent copy of each
variable in each instance of the class. You call a nonshared procedure using
a variable pointing to a specific instance of the class. Any variable in
that instance is independent of a variable with the same name in another
instance. Therefore, they can hold different values.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top