Synchronizing Access to a member of the ASP.NET session
Posted
by Sam
on Stack Overflow
See other posts from Stack Overflow
or by Sam
Published on 2010-04-26T17:33:57Z
Indexed on
2010/04/26
17:53 UTC
Read the original article
Hit count: 308
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 UserSession object for the user.
Each Ajax call needs a UserSession object.
Data in the UserSession object is unique to each user.
Originally, during each Ajax call I would create a new UserSession object and it's data members were stored in the ASP.NET Session. However, I found that the UserSession object was being instantiated a lot. To minimize the construction of the UserSession object, I wrapped it in a Singleton pattern and sychronized access to it.
I believe that the synchronization is happening application wide, however I only need it to happen per user. I saw a post here that says the ASP.NET cache is synchronized, however the time between creating the object and inserting it into the cache another Thread could start construction it's another object and insert it into the cache.
Here is the way I'm currently synchronizing access to the object. Is there a better way than using "lock"... should be be locking on the HttpContext.Session object?
private static object SessionLock = new object();
public static WebSession GetSession
{
get
{
lock (SessionLock)
{
try
{
var context = HttpContext.Current;
WebSession result = null;
if (context.Session["MySession"] == null)
{
result = new WebSession(context);
context.Session["MySession"] = result;
}
else
{
result = (WebSession)context.Session["MySession"];
}
return result;
}
catch (Exception ex)
{
ex.Handle();
return null;
}
}
}
}
© Stack Overflow or respective owner