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?

Was it helpful?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top