锁定静态变量
我在服务器端有一个以下课程。
public class Sample
{
private enum Status
{
NotEvaluated,
Yes,
No
}
private static object _lockObj = new object();
private static Status _status = Status.NotEvaluated;
public static Status GetStatus()
{
if (_status == Status.NotEvaluated)
{
lock (_lockObj)
{
if (_status == Status.NotEvaluated)
{
//some evaluation code which sets status to either Yes/No;
_status = Status.Yes;
}
}
}
return _status;
}
}
上面的锁定机制有问题吗?我需要锁定吗?因为它是服务器端的(会有多个请求)并且变量是静态的,所以我认为应该在评估时锁定它。
如果我错了请纠正我。
谢谢
I have a following class at server-side.
public class Sample
{
private enum Status
{
NotEvaluated,
Yes,
No
}
private static object _lockObj = new object();
private static Status _status = Status.NotEvaluated;
public static Status GetStatus()
{
if (_status == Status.NotEvaluated)
{
lock (_lockObj)
{
if (_status == Status.NotEvaluated)
{
//some evaluation code which sets status to either Yes/No;
_status = Status.Yes;
}
}
}
return _status;
}
}
Is anything wrong in locking mechanism above? do i need to lock at all? Because it is server-side (multiple requests will be there) and the variable is static i would think it should be locked at the time of evaluation.
correct me if i am wrong.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不/不应该对“if (_status == Status.NotEvaluated)”进行外部检查。虽然如果您离开它,似乎不会发生任何“坏”事情,但第二个线程可能会在第一个线程将 _status 设置为 Status.Yes 之前不必要地输入该“if”。是的,您需要锁定:
“作为基本规则,您需要锁定访问任何可写共享字段。”
http://www.albahari.com/threading/part2.aspx
You do not/should not have the outer check for "if (_status == Status.NotEvaluated)". While it appears that nothing "bad" would happen if you left it it, there is the possibility that a second thread may enter that "if" needlessly, just prior to the first thread setting _status to Status.Yes. And yes, you need to lock:
"As a basic rule, you need to lock around accessing any writable shared field."
http://www.albahari.com/threading/part2.aspx