I have a class that has a decimal property accessible from multiple threads
public class MyObject
{
public decimal MyProperty{get; set;}
}
Should i use locks inside of get & set?
I understand that decimal is not the type operations with are atomic and decimal uses 96 bits.
Buy it feels very awkward to write locks only for these kinds of types – especially if you are not entirely sure why you doing this.
No, operations on decimal are not atomic.
The CLR only guarantees atomicity for reading/writing 32 bit values, and reference sized values. A decimal consists of multiple 32 bit ints, and operations on it are thus not atomic.
But usually properties don’t need to be thread safe. Typically you use locking on a higher level, where the code knows more about what locking you need.
Even if you’d use locking in the property getter and setter, a simple operation like
MyProperty+=1wouldn’t be thread safe.