Is a string property itself threadsafe?

前端 未结 5 2121
一个人的身影
一个人的身影 2020-12-08 10:09

String\'s in C# are immutable and threadsafe. But what when you have a public getter property? Like this:

public String SampleProperty{
    get;
    private          


        
5条回答
  •  渐次进展
    2020-12-08 10:47

    Your second code sample is definitely not right, because locks only have the desired effect when they are used in all places where the variable is accessed (both for get and set), so the get would also need a lock.

    However, when getting and setting a reference-type field as a property like this, then adding a lock statement doesn't add any value. Assignments to pointers are guaranteed to be atomic in the .NET environment, and if multiple threads are changing a property then you have an inherent race condition anyway (where threads may see different values; this may or may not be a problem) so there's little point in locking.

    So for what it does, the first piece of code is fine. But whether you really want to build inherent race conditions into a multi-threaded application is another matter.

提交回复
热议问题