3

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

1 Answer 1

2

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

lock (_lockObj) { if (_status == Status.NotEvaluated) { // some evaluation code which sets status to either Yes/No; _status = Status.Yes; } return _status; } 
Sign up to request clarification or add additional context in comments.

1 Comment

I'm guessing OP was trying to optimize by not locking when he KNOWS that he doesn't have to, but the lock() is fairly lightweight - this is not an optimization that you need to do.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.