C# thread safety with get/set

前端 未结 9 877
谎友^
谎友^ 2020-11-27 15:01

This is a detail question for C#.

Suppose I\'ve got a class with an object, and that object is protected by a lock:

Object mLock = new Object();
MyOb         


        
9条回答
  •  一向
    一向 (楼主)
    2020-11-27 15:36

    Concurrent programming would be pretty easy if your approach could work. But it doesn't, the iceberg that sinks that Titanic is, for example, the client of your class doing this:

    objectRef.MyProperty += 1;
    

    The read-modify-write race is pretty obvious, there are worse ones. There is absolutely nothing you can do to make your property thread-safe, other than making it immutable. It is your client that needs to deal with the headache. Being forced to delegate that kind of responsibility to a programmer that is least likely to get it right is the Achilles-heel of concurrent programming.

提交回复
热议问题