Do we need to lock when we get the property in C#
-
27-10-2019 - |
Question
In C#, is it necessary to lock when getting a non volatile property? I know we need to lock when setting the property. how about getting?
Now 3.0 provide automatic property, is it thread safe itself?
Solution
No, automatic properties are not thread-safe. They are nothing more than syntactic sugar; the compiler automatically generates the private backing fields, just as if you'd written them out manually.
However, unless your application is accessing properties from multiple threads, there's no reason to worry about this in the first place. It's hard to tell from your question if your app is multi-threaded.
OTHER TIPS
Yes. If multiple threads are reading/writing to the same property, you will have to lock it.
Automatic properties are nothing more than syntactic sugar and don't lock.
No. You still need to lock if you're accessing the property from multiple threads.
I'd say that depends on the type of the property. If it can be read atomically (like an int or a pointer) than the read is safe.
However if you access an object through a property, then multiple threads can access that object simultaniously.
but a lock in the getter/ setter would'nt helpe here either.
hth
Mario