C# thread safety with get/set

No, your code won’t lock access to the members of the object returned from MyProperty. It only locks MyProperty itself.

Your example usage is really two operations rolled into one, roughly equivalent to this:

// object is locked and then immediately released in the MyProperty getter
MyObject o = MyProperty;

// this assignment isn't covered by a lock
o.Field1 = 2;

// the MyProperty setter is never even called in this example

In a nutshell – if two threads access MyProperty simultaneously, the getter will briefly block the second thread until it returns the object to the first thread, but it’ll then return the object to the second thread as well. Both threads will then have full, unlocked access to the object.

EDIT in response to further details in the question

I’m still not 100% certain what you’re trying to achieve, but if you just want atomic access to the object then couldn’t you have the calling code lock against the object itself?

// quick and dirty example
// there's almost certainly a better/cleaner way to do this
lock (MyProperty)
{
    // other threads can't lock the object while you're in here
    MyProperty.Field1 = 2;
    // do more stuff if you like, the object is all yours
}
// now the object is up-for-grabs again

Not ideal, but so long as all access to the object is contained in lock (MyProperty) sections then this approach will be thread-safe.

Leave a Comment