问题
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?
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/8806810/should-this-singleton-be-thread-safe-in-an-asp-net-app