c# - locking static variable -


i have following class @ 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 sets status either yes/no;                     _status = status.yes;                 }             }         }          return _status;     }  } 

is wrong in locking mechanism above? need lock @ all? because server-side (multiple requests there) , variable static think should locked @ time of evaluation.

correct me if wrong.

thanks

you not/should not have outer check "if (_status == status.notevaluated)". while appears nothing "bad" happen if left it, there possibility second thread may enter "if" needlessly, prior first thread setting _status status.yes. , yes, need lock:

"as basic rule, need lock around accessing writable shared field." http://www.albahari.com/threading/part2.aspx

lock (_lockobj)    {       if (_status == status.notevaluated)          {             // evaluation code sets status either yes/no;             _status = status.yes;          }       return _status;       } 

Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -