开发者

Where does static variable work in ASP.NET page?

开发者 https://www.devze.com 2022-12-28 09:56 出处:网络
I had an interview today and every thing was going very good, but then an interviewer asked me a question Where Does Static Variable Work in C#- At Application Level or At Page Level.

I had an interview today and every thing was going very good, but then an interviewer asked me a question Where Does Static Variable Work in C#- At Application Level or At Page Level.

I was not very much clear about this answer as I only knew that static variables are stored on heap and I didn't knew anything about web related thing.

Then he tried to make me more clear by giving an example that in a page I am using static variable and three users are accessing the page one of the user updates the value of static variable, What value will be visible to remaining two users an old copy or the update will be r开发者_如何学编程eflected.


Unless it's [ThreadStatic], a static variable will only have one value for each AppDomain.

In ASP.Net, each application has its own AppDomain, so static variables will be shared by all requests in the application. This is what the interviewer was getting at – using static variables in ASP.Net applications is a common mistake that can lead to mysterious corruption errors when multiple requests happen at once.


After one page changes the value, the other pages would all get the updated value.

This may or may not be what you want. This is why static variables are dangerous in web programming. In a Winforms application for example, a static variable works fine to store values that are global for this process, as there is likely just one process running. You get the expected behavior.

In a web application however, your code can be started in multiple threads in the same AppDomain. Developers are sometimes surprised when the value is shared.

If you want the values to be different (you usually do), you can force this using the ThreadStatic attribute. Different web request are in different threads, so they will remain ignorant of each other. I never use this since I don't trust garbage collection to get rid of the value before the next page call, which might reuse the same thread. Likewise, I wouldn't trust static variables for purposefully sharing values between asp.net threads; use a server variable.


Static variables in C# with ASP.NET work at the application level.

As far as what value they would get, it depends on if they access the variable before or after the page updates the static variable. If they get the value before the static variable is changed, they will see the old value. If they get the value after the static variable is changed, they will get the new value. Static variables can be troublesome in ASP.NET, I would suggest they only be used for constant values or for read-only, immutable classes.

0

精彩评论

暂无评论...
验证码 换一张
取 消