Synchronizing Access to a member of the ASP.NET session

后端 未结 2 738
心在旅途
心在旅途 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: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"];
    

提交回复
热议问题