Asp.net Static Variable Life time Across Refresh and PostBack

WorkAround:

I have declared a class level Public static variable and initialized with a value 0 in the environment of ASP.NET 3.5
In load event I Incremented by 1 of that variable

Problem:

  1. After getting page refresh and even Postback, I am getting latest values of that variable.
    A variable declared as STATIC , not getting reset by Page refresh and Postback?
  2. I just close the browser and close the VS 2008 IDE – even though while i am reopen, rerun the same web application, I am getting last incremented value, Not 0.
    I am wondering how this is possible after i close application.

Could you please help on this.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Static variables are valid for the entire AppDomain. When you close your browser you don’t close the application as it continues to execute on the web server. Oh and forgot to mention: try to avoid using static variables in multi-threaded applications without proper locking mechanisms or you may run into race conditions.

Method 2

Static variables keep their values for the duration of the application domain.

It will survive many browser sessions until you restart the web server (IIS) or until it restarts on its own (when it decides it needs to refresh its used resources).

Method 3

Static variables are valid for the
entire AppDomain.

Closing VS 2008 IDE and/or stopping debugging is not always enough to get the AppDomain that is hosting your website to such down. (Even when the website is hosted in the Vs 2008 tests server.

One easy solution is the “touch” the
web.config file. (E.g. add a space
and save it)

That will get the next request processed in a new app-domain.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x