3

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?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
user705414
  • 20,472
  • 39
  • 112
  • 155
  • possible duplicate of [Are C# auto-implemented static properties thread-safe?](http://stackoverflow.com/questions/2074670/are-c-auto-implemented-static-properties-thread-safe) – Cody Gray - on strike May 02 '11 at 12:18

4 Answers4

4

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.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
4

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.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • I think that an automatic property is always thread safe, since it is only the return statement. (if the propertyt type is a struct I am not so sure...). However, I think, that you have to be careful, since what you return from a property is in no way secured against concurrency in any way. – Mario The Spoon May 02 '11 at 12:07
  • @Mario: Automatic properties are not "only the return statement". They also include a setter, which is not thread safe for obvious reasons. But even a getter is not *necessarily* thread-safe. – Cody Gray - on strike May 02 '11 at 12:10
  • ok, depends on the data type, everything that can be atomically manipulated is thread safe though (so only monsters like doubles or floats come to my mind right now) - again I haven't made up my mind about struct... – Mario The Spoon May 02 '11 at 12:11
2

No. You still need to lock if you're accessing the property from multiple threads.

Russell Troywest
  • 8,635
  • 3
  • 35
  • 40
1

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.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Mario The Spoon
  • 4,799
  • 1
  • 24
  • 36