Synchronizing Access to a member of the ASP.NET session

后端 未结 2 713
心在旅途
心在旅途 2021-01-13 18:27

I\'m building a Javascript application and eash user has an individual UserSession. The application makes a bunch of Ajax calls. Each Ajax call needs access to a single User

相关标签:
2条回答
  • 2021-01-13 19:05

    You don't need to lock Session state access.

    The physical values of a session state are locked for the time needed to complete a request. The lock is managed internally by the HTTP module and used to synchronize access to the session state.

    http://msdn.microsoft.com/en-us/library/aa479041.aspx

    0 讨论(0)
  • 2021-01-13 19:07

    In general, you don't need this kind of code for asp.net session access, since access to each session is limited to a single user. The only reason I can think of for locking access to your session object is if you expect to have multiple simultaneous ajax requests, and even so, I think asp.net would synchronize the access for you.

    If you do decide to lock, you only really need to do it if your session object is null:

    if (context.Session["MySession"] == null) {
      lock(SessionLock) {
        if (context.Session["MySession"] == null) {
          context.Session["MySession"] = new WebSession(context);  // try-catch block removed for clarity (and my laziness)
        }
      }
    }
    return (WebSession)context.Session["MySession"];
    
    0 讨论(0)
提交回复
热议问题