3

Note that "singleton" used in slightly uncommon sense - "object visible as single instance like HttpContext.Current" unlike normal "object with one shared instance".

I make use of a singleton type of UserContext class for my asp.net MVC applications. This class allows me to store user data as a strongly-typed session object. I ran across this CodeReview question and wondered if it was necessary to be concerned about thread safety in this application context.

Here's a simplification of my code:

public class UserContext
{
    private UserContext()
    {
    }

    public static UserContext Current
    {
        get
        {
            if (HttpContext.Current.Session["UserContext"] == null)
                BuildUserContext();

            return (UserContext)HttpContext.Current.Session["UserContext"];
        }
    }

    private static void BuildUserContext()
    {
        if (!user.Identity.IsAuthenticated) return;

        var uc = new UserContext { IsAuthenticated = true };

        // ...snip...
        // Set up user data

        // Save it into the session
        HttpContext.Current.Session["UserContext"] = uc;
    }


    #region Class members
    public bool IsAuthenticated { get; internal set; }
    public string Name { get; internal set; }
    // ...snip...
    // Other properties

    public void Refresh()
    {
        BuildUserContext();
    }

    public void Flush()
    {
        HttpContext.Current.Session["UserContext"] = null;
    }
    #endregion
}

I haven't had any locking issues so far, but right now the site is not very high traffic. Should I adopt Jon Skeet's thread-safe model or does IIS manage that for me?

Community
  • 1
  • 1
Josh Anderson
  • 5,975
  • 2
  • 35
  • 48
  • Where is "singleton" in your sample? Code is reasonable, but the object is not "singleton" in any usual sense (object with one instance - http://en.wikipedia.org/wiki/Singleton_pattern)... Would be huge problem if actually used as singleton. – Alexei Levenkov Jan 10 '12 at 17:06
  • Yeah, I actually paused before including the word "singleton" in the title, but I didn't have a more efficient way of describing it. Within the context of a session it's a singleton, but you're right, it's not an application-wide singleton. My question is more about how threading is handled and whether this could present problems. – Josh Anderson Jan 10 '12 at 17:09

2 Answers2

3

Access the Session is already Thread safe.

In general as long as you access any shared state in your static properties in a thread-safe manner, you won't have any problems.

Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
1

ASP session state comes with a synchronizing logic. If the executed page needs write access to the session state, the session state is locked and other request on the same session has to wait until the first one finishes.

See Synchronizing Access to the Session State.

Guillaume
  • 12,824
  • 3
  • 40
  • 48