静态类访问会话
问题描述:
我有类,它具有我使用的所有会话变量,你可以让我知道它是否线程安全。静态类访问会话
public static class AppSession
{
private const string UserIdKey = "UserId";
public static int UserId
{
get { return GetSession<int>(UserIdKey); }
set { SetSession(UserIdKey, value); }
}
private static T GetSession<T>(string key)
{
var currentSession = HttpContext.Current.Session;
if (currentSession == null) return default(T);
if (currentSession[key] != null)
return (T) currentSession[key];
return default(T);
}
}
访问属性AppSession.UserId时它将是线程安全的。
答
是的。每个请求都有自己的会话,并且会话是线程安全的,因为:
“会话状态模块实现读取器/写入器锁定机制并将访问权排队到状态值。具有会话状态写入权限的页面将保留一个作家锁定会话,直到请求终止。“
请参阅https://msdn.microsoft.com/en-us/library/aa479041.aspx?f=255&MSPPError=-2147217396