Search code examples
c#multithreadingpropertiessynclock

Should synclock be used on properties?


I have been reading around and am getting conflicting answers on whether I should or should not use synclock on properties.

I have a multi-threaded application that needs to get/set properties across threads on instance objects. It is currently implemented without using synclock and I have not noticed any problems so far. I am using synclock on common static methods but I'd like to implement my instance classes properly and in a thread safe way.

Any feedback would be greatly appreciated.


Solution

  • A good rule of thumb is that you need to lock if any of the following conditions hold true:

    • if any field of an object is going to be modified on more than one thread
    • if any modifications involve accessing more than one field
    • if any modifiable field is a Double, Decimal, or structured value type
    • if any modifications involve read-modify-write (i.e. adding to a field or setting one field with the value from another)

    then you probably need to lock in every method or property that accesses those fields.

    EDIT: Keep in mind that locking inside of a class is rarely sufficient -- what you need to do is make sure that things don't go wrong across the span of an entire logical operation.

    As @Bevan points out, if calling code needs to access an object more than once, the client code should take out its own lock on the object for the entire duration of its work to ensure that another thread doesn't get "in between" its accesses and foul up its logic.

    You also need to take care that if anything needs to take out multiple locks at once, that they always be taken in the same order. If thread 1 has a lock on instance A and tries to lock instance B, and thread 2 has a lock on instance B and tries to get a lock on instance A, both threads are stuck and unable to proceed -- you have a deadlock.