c# - Are checks for null thread-safe? -


i have code exceptions thrown on new thread need acknowledge , deal on main thread. achieve sharing state between threads using field holds thrown exception.

my question do need use locks when checking null doing in following code sample?

public class myclass {     readonly object _exceptionlock = new object();     exception _exception;      public myclass()     {         task.run(() =>         {             while (checkisexceptionnull())             {                 // conditional return true if 'something has gone wrong'.                 if(checkifmycodehasgonewrong())                 {                     lock(_exceptionlock)                     {                         _exception = new gonewrongexception();                     }                 }             }         });     }      bool checkisexceptionnull() // method necessary?     {         lock (_exceptionlock)         {             return _exception == null;         }     }      // method gets fired periodically on main thread.     void rethrowexceptionsonmainthread()     {         if (!checkisexceptionnull())         {             lock (_exceptionlock)             {                 throw _exception; // throw need in lock?             }         }     } } 

additionally, do need use lock when throwing exception on main thread?

the first thing note code not thread safe because have thread race: check checkisexceptionnull in different locked region throw, but: the value can change between test , throw.

field access not guaranteed thread safe. in particular, while references cannot torn (that guaranteed - reads , writes of references atomic), not guaranteed different threads see latest values, due cpu caching etc. unlikely bite you, that's problem threading issues in general case ;p

personally, i'd make field volatile, , use local. example:

var tmp = _exception; if(tmp != null) throw tmp; 

the above has no thread race. adding:

volatile exception _exception; 

ensures value isn't cached in register (although technically side-effect, not intended / documented effect of volatile)


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

c# - Exception when attempting to modify Dictionary -