1

if I have a property of TimeSpan in my class, that is accessed by multiple threads (both read and write), do I have to lock on something while reading/writing to it? Putting lock (_some_object) inside both get and set for instance?

I've read that properties are not thread safe. But I don't know how it works specifically with structs. What I want is to avoid unexpected behaviour or crash while writing to the property and reading it at the same time. I've also read a lot about atomicity, immutability ..

But I'm still not sure if I have to concern in my specific case.

Do I have to do something like this?

public TimeSpan MinDataTimeStep
{
    get 
    {
        lock (mMinDataTimeStepLock)
        {
            return mMinDataTimeStep;
        }
    }
    set
    {
        lock (mMinDataTimeStepLock)
        {
            mMinDataTimeStep = value;
        }
    }
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • Whether or not this is safe with or without a lock is dependent on how it's used. All permutations are possible. – Servy Oct 21 '14 at 14:42

0 Answers0