【发布时间】:2015-02-20 07:22:52
【问题描述】:
根据我目前的理解,我认为这段代码不是线程安全的,但想确认一下。换句话说,我认为,尽管极不可能,但表示不同 HTTP 请求的多个线程可能会混淆_userName 属性的值。
public class SomeClass
{
private static string _userName;
public static string UserName
{
get
{
if (string.IsNullOrEmpty(_userName))
{
_userName = HttpContext.Current.User.Identity.Name;
}
return _userName;
}
}
}
它是线程安全的吗?如果不是,是否会删除 null 检查,并且始终直接(在静态属性中)访问 HttpContext.Current.User.Identity.Name 是线程安全的?
public class SomeClass
{
public static string UserName
{
get
{
return HttpContext.Current.User.Identity.Name;
}
}
}
【问题讨论】:
-
正确,您的第一个示例不是线程安全的,因为静态成员在线程之间共享(除非您使用线程本地存储,但您不是),并且
HttpContext.Current属性 被存储在线程本地存储中。 -
另外,还有第二个线程安全问题:你的线程可能在
if和=语句之间被抢占,所以你想要一个lock,而不是他的代码很好首先是想法。 -
“虽然可能性极小” 这可能比你想象的要大得多。
标签: c# asp.net asp.net-mvc multithreading thread-safety