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

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

    It is stated also documentation under topic "Managed Threading Best Practices". https://msdn.microsoft.com/en-us/library/1c9txz50(v=vs.110).aspx

    It says;

    Don't use types as lock objects. That is, avoid code such as lock(typeof(X)) in C# or SyncLock(GetType(X)) in Visual Basic, or the use of Monitor.Enter with Type objects. For a given type, there is only one instance of System.Type per application domain. If the type you take a lock on is public, code other than your own can take locks on it, leading to deadlocks. For additional issues, see Reliability Best Practices.

    Use caution when locking on instances, for example lock(this) in C# or SyncLock(Me) in Visual Basic. If other code in your application, external to the type, takes a lock on the object, deadlocks could occur.

提交回复
热议问题