Some experiences of using static variables under ASP.NET

xiaoxiao2021-03-06  47

During the recent work, a colleague is an item, discovers a problem, a B / S web system, a user logs in to the publishing information, and B users also log in to the publishing information, at this time, when the A user, on the page should display a The user's content and A user's signature are the same for B users, and the information will not be confused. But actually A users show a signature of A users and B users. Similar to confusion also appeared in another system project I participated, while multiple users log in to access, fill in information, and confused with each other.

In the project source code, the user ID is unique. With the session pass, the session of different login users will not be the same, should not be confused, and we found that we use the Static variable in large quantities. The original intention is to use as a global variable. Make information about different users will not be confused. But it seems that the actual effect is the opposite of the idea.

I was still busy with another project, and I didn't want to solve the problem. The colleague passed the analysis, initially solved this problem, in order to avoid your forget, organize some ideas, and wake up for yourself.

Mainly the scope of the STATIC variable needs to be clear

A Static variable is defined in a class, only in the same execution context, all users access to the same variable. That is to say, in a class define a static variable all user access is the same variable, Static's scope is obviously the application level, not the session level (page level). From this perspective, the Static UserID variable is defined, the A user login system, assigns the userid A, userid = a, before A did not publish information, the value of the userid maintains a constant, this time B user logs in, the same, UserID assignment B, because the Static action range is the application level, all users share this Static variable, so the value of the userID variable is no longer A but B. Next, the A user submits the release information, and the userid is B, so the final display user signature is no longer A but b is, it has confused.

This analysis is clear. On the page level, it is forbidden to use the Static variable to modify the normal variable. Using ViewState, the question is resolved;

Blog

The issue mentioned by Meyer's blogs also mentioned that his article also gave me a lot of revelation.

Make a note of this problem and remind yourself.

转载请注明原文地址:https://www.9cbs.com/read-81784.html

New Post(0)