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

前端 未结 6 2093
自闭症患者
自闭症患者 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:39

    It's the same problem as with lock(this) - you're locking on a reference which other code has access to, so it could be locking on it too.

    If you have two unrelated pieces of code locking on the same reference without intending to exclude each other, then in the best case you could lose a bit of performance due to a lack of concurrency - and in the worst case you could introduce a deadlock.

提交回复
热议问题