不,您的代码不会锁定对从返回的对象的成员的访问
MyProperty。它只会锁定
MyProperty自己。
您的示例用法实际上是将两个操作合而为一,大致等效于此:
// object is locked and then immediately released in the MyProperty getterMyObject o = MyProperty;// this assignment isn't covered by a locko.Field1 = 2;// the MyProperty setter is never even called in this example
简而言之-如果两个线程
MyProperty同时访问,则getter将短暂阻塞第二个线程,直到将对象返回到第一个线程为止, 但
随后它将把对象也返回到第二个线程。然后,这两个线程将具有对该对象的完全的,未锁定的访问权限。
编辑以回答问题中的更多详细信息
我仍然不能100%地确定要实现的目标,但是如果您只想对对象进行原子访问,那么您是否无法将调用代码锁定在对象本身上呢?
// quick and dirty example// there's almost certainly a better/cleaner way to do thislock (MyProperty){ // other threads can't lock the object while you're in here MyProperty.Field1 = 2; // do more stuff if you like, the object is all yours}// now the object is up-for-grabs again这不是理想的方法,但是只要所有对对象的访问都包含在
lock (MyProperty)各个节中,则此方法将是线程安全的。



