String’s in C# are immutable and threadsafe. But what when you have a public getter property? Like this:
public String SampleProperty{ get; private set; }
If we have two threads and the first is calling ‘get’ and the second is calling ‘set’ at the ‘same’ time, what will happen?
IMHO the set must made a lock to be thread-safe like this:
private string sampleField; private object threadSafer = new object(); public String SampleProperty{ get{ return this.sampleField; } private set{ lock(threadSafer){ sampleField = value; } } }
Most of the answers are using the word ‘atomic’ as if atomic changes are all that are needed. They’re not, usually.
This has been mentioned in the comments, but not usually in the answers – that’s the only reason for me providing this answer. (The point about locking at a coarser granularity, to allow things like appending, is entirely valid as well.)
Usually you want a reading thread to see the latest value of the variable/property. That isn’t guaranteed by atomicity. As a quick example, here’s a bad way to stop a thread:
DoWorkmay well loop forever, despite the write to the boolean variable being atomic – there’s nothing to stop the JIT from caching the value ofstoppinginDoWork. To fix this, you either need to lock, make the variablevolatileor use an explicit memory barrier. This all applies to string properties as well.