Why is “lock (typeof (MyType))” a problem?

前端 未结 6 2094
自闭症患者
自闭症患者 2020-12-14 00:00

MSDN gives the following warning about the lock keyword in C#:

In general, avoid locking on a public type, or instances beyond yo

6条回答
  •  甜味超标
    2020-12-14 00:53

    because the target of a lock is ONLY to establish a place to store the lock boolean (Am I locked or not) for other threads to look at....

    The common misconception that the target of a lock is actually somehow being locked is just wrong... What is "locked" is, .... nothing, unless in methods which can access some shared memory in an unsafe manner, you write the code to look at the this lock and not proceed until it has been released... using a Type object, as a lock target is wrong because code snippets anywhere in the entire solution process space can access that type object and change the synch block that the lock boolean is stored in. Creating a locally scoped object allows you to better ensurethat only those threads and methods that can access or mess with your "at risk" shared memory can also access and/or modify the lock.

提交回复
热议问题