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?
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?
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, 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.
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 simultaneously.
but a lock in the getter/ setter wouldn't help here either.