C# thread safety with get/set

前端 未结 9 926
谎友^
谎友^ 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:38

    The lock scope in your example is in the incorrect place - it needs to be at the scope of the 'MyObject' class's property rather than it's container.

    If the MyObject my object class is simply used to contain data that one thread wants to write to, and another (the UI thread) to read from then you might not need a setter at all and construct it once.

    Also consider if placing locks at the property level is the write level of lock granularity; if more than one property might be written to in order to represent the state of a transaction (eg: total orders and total weight) then it might be better to have the lock at the MyObject level (i.e. lock( myObject.SyncRoot ) ... )

提交回复
热议问题