Are static objects unique per user?

2019-06-16 12:49发布

I have a .net application (c#) that goes something like this

public partial class _Default : System.Web.UI.Page
{
    #region initial variables setup

    private static exam theExam;

    #endregion


    protected void Page_Load(object sender, EventArgs e)
    {
       if(!IsPostBack)
       {
        string userid = Request.Querystring["user"].ToString();
           theExam = new exam(userid, "some values");
       }
    }
// rest of code.

Now my question is, if user 105 logs in an instance of exam theExam is created and assign to the static declaration on top. If user 204 then logs in from a different computer, does the static object at the top gets the value of 204 even on user's 105's computer?

5条回答
SAY GOODBYE
2楼-- · 2019-06-16 13:44

No, the static object is the same instance for everyone logged on. Also the object doesn't live on 105's computer but just on the web server ofcourse.

查看更多
够拽才男人
3楼-- · 2019-06-16 13:49

Lifetime of static variables and user sessions are very different concepts. Static variables have a lifetime defined by the CLR and essentially boils down to the following 2 rules

  1. There is one storage location for a static variable per AppDomain
  2. Each unique instatiation of a generic type creates a different static variable.

I'm finding it hard to write the second rule without it being ambiguous as to unique. Essentially MyType<int> and MyType<string> each have different static variables. While MyType<int> and MyType<int> share the same one.

User's acess to a web server don't affect either of these.

If you want to have per user data then use the Session to store the data.

Session["examKey"] = theExam;
查看更多
神经病院院长
4楼-- · 2019-06-16 13:50

Short answer: yes, the static field is global to the AppDomain, so doing this for one user will step on the data for another user.

You probably want to look into using Session storage instead, which is scoped per-user, e.g.

var theExam = Session["exam"] as Exam;
查看更多
可以哭但决不认输i
5楼-- · 2019-06-16 13:51

There is one "instance" of a static object per AppDomain. So the answer to your question is yes. Since you overwrite the variable when user 204 logs in, the same value will appear for user 105, too.

Some general advices

  • Avoid static fields wherever possible
  • Use the Session for storing temporary information in the context of a user's browsing session
    Session["exam"] = currentUser.Exam;
  • Use a Profile Provider for persisting information about each user between sessions.
查看更多
相关推荐>>
6楼-- · 2019-06-16 13:52

There's also a [ThreadStatic] attribute in .Net that will make one static instance per thread.

http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(VS.71).aspx

查看更多
登录 后发表回答