“lifespan” of .NET public static variables?

2019-07-19 02:55发布

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?

6条回答
何必那么认真
2楼-- · 2019-07-19 03:11

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.

查看更多
我命由我不由天
3楼-- · 2019-07-19 03:13

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?

查看更多
贪生不怕死
4楼-- · 2019-07-19 03:24

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.

查看更多
ゆ 、 Hurt°
5楼-- · 2019-07-19 03:26

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.

查看更多
小情绪 Triste *
6楼-- · 2019-07-19 03:30

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.

查看更多
Summer. ? 凉城
7楼-- · 2019-07-19 03:35

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.

查看更多
登录 后发表回答