“lifespan” of .NET public static variables?

2019-07-19 02:54发布

问题:

I did a little experiment. On the LoginButton_Click() event from a Login.aspx button, I have a code that does something like:

MyClass.MyPublicStaticString = LoginNameTextBox.Text;

After logging in it goes to Default.aspx by FormsAuthentication. On Default.aspx, I have a code on Page_Load() like this:

Label1.Text = MyClass.MyPublicStaticString.ToString();

After waiting for a few minutes, Label1.Text becomes empty even before my login timeout expires.

What is happening here?

回答1:

Static fields are (unless [ThreadStatic]) one instance per app-domain, meaning: all requests share the same value. You need to be exceptionally careful using static in a web application. If in doubt: don't.

Re lifetime; the AppDomain; they won't be collected while assigned to the static field, and will expire if the App-Pool recycles in IIS.



回答2:

It is possible to use the Application State object. However it holds information that will persist for as long as the application is running. Session State, on the other hand has a lifetime that is tied to the visit by the current user, plus a default of 20 minutes thereafter to verify the s/he is not just snacking temporarily and using a slow network. Besides, ApplicationState is visible / accessible to all user contexts; while Session is visible and accessible only in the context of the current user. On the third hand, Postbacks are limited in context to the context of the last page sent from the Server, because a postback happens when the Browser returns the Page to the Server including the result(s) of the user action(s). The lifecyle of the Page is different from that of the Session, and that of the ApplicationState, and should not be confused, any one with any other.



回答3:

I've never worked with ASP.NET, but I can tell you that static variables do not expire, or anything like that.

My best is that this has to do with another request resetting the variable somehow, or possibly even re-launching the whole application, creating a brand new memory space, and obviously without the previous static value.



回答4:

You should really be using Session State for this kind of thing.
If you don't, two users logging in within short period of time will both get last user's name because it was stored last in MyPublicStaticString.



回答5:

I think your application's Page class is not longer in memory at your webserver thats why your static variable disappers but your authentication cookie is still valid as your asp.net forms authentication timeout may not be expired yet.



回答6:

Is it possible to use the ASP.NET Application State object instead as in ASP.NET this will also maintain state across multiple Postbacks / Sessions?