简体   繁体   中英

Public Shared Variable Shared Between Users?

I've taken over the maintenance of the website (ASP.NET VB) and on one particular page I noticed the below code

Inherits System.Web.UI.Page

Public Shared UserNumber As String

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init

    UserNumber = Session("UserNumber")

    ...

End Sub

My question is whether the variable UserNumber can be accessed or changed by any other user than the current one?

Many thanks

A Shared variable is the same as a static variable in C#.

These can be shared across all instances, therefore different users would share the same variable.

Looking at the variable name, I would assume you would need to remove this Shared


You are applying a Session variable value to the Shared String on Page_Init .

Therefore each time the user loads the page, their session variable will override the current value.


If you are not using this variable outside of this class, then I would recommend changing it to:

Protected UserNumber As String

EDIT My initial answer was incorrect. Trying again...

Technically, as @Curt indicated, a Shared variable is shared across instances of the class.

However, with the code as is, it is less likely that the value will be shared amongst users as it is set to each user's local copy of the value in their Session in Page_Init .

There is a possible "race condition" where after the shared variable UserNumber has been initialised in Page_Init , and another user submits a request which updates the value of that variable from their session, the first user will then see the second user's value. ie users can see other user's values for concurrent requests.

Instead, I recommend using a ReadOnly non-shared property to get the value from the Session once:

 Private mUserNumber As String
 Public ReadOnly Property UserNumber As String
      Get
           If String.IsNullOrEmpty(mUserNumber) Then
               mUserNumber = Session("UserNumber")
           End If
           Return mUserNumber
      End Get
 End Property

This uses a pattern called "Lazy-loading", which I use in read-only properties a lot on pages to improve performance and readability of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM