Search code examples
c#.netpropertiesthread-safetyautomatic-properties

Do we need to lock when we get the property in C#


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.