是否有 .Net StyleCop 规则警告有关 lock(this)、lock(typeof、lock(等) 的问题?
这三种类型的锁显然都是不好的。 还有哪些其他类型的锁定是不好的? 有 Stylecop / FxCop 规则可以解决这个问题吗? 如果没有,那么您能帮我实现自定义规则吗?他们的代码一定是相似的,对吧?
谢谢。
These 3 types of lock are apparently bad.
What other type of locking is bad?
Are there Stylecop / FxCop rules that would catch this?
If not, then would you please help me with a custom rule implementation? They code for all of them must be similar, right?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
John Robbins 的 示例(您可能需要允许浏览器中的弹出窗口) ://www.wintellect.com/Resources/Books" rel="nofollow noreferrer">调试 Microsoft .NET 应用程序一书包含此类 FxCop 规则的源代码(DoNotLockOnPublicFields、DoNotLockOnThisOrMe、DoNotLockOnTypes 等)。看起来它们最初是为 FxCop 1.35 制作的,而 VS 2008 中的版本和最新的独立版本是 1.36(更不用说 VS2010 了)。所以他们可能需要一些调整,YMMV。
还有规则 CA2002 (不要锁定身份较弱的对象),它会检查诸如
lock(typeof(...))
之类的内容,但不会检查lock(this)
The samples (you may need to allow popups in your browser) of John Robbins' Debugging Microsoft .NET Applications book contain sources for such FxCop rules (DoNotLockOnPublicFields, DoNotLockOnThisOrMe, DoNotLockOnTypes, etc.). It looks like they were originally made for FxCop 1.35, whereas the version in VS 2008 and the latest standalone version is 1.36 (not to speak of VS2010). So they might need some tweaking, YMMV.
There is also rule CA2002 (Do not lock on objects with weak identity), which checks for stuff like
lock(typeof(...))
, but not forlock(this)
基本上,您不应该锁定任何外部对象,除非这是专门的锁定对象(例如非通用
ICollection
上的SyncRoot
属性的设计目的)。这样做会带来引用的其他“用户”也锁定它的风险,从而导致不必要的锁定甚至死锁。显然,
this
和typeof()
根据定义是外部对象。字符串是不可变的,并且字符串文字都被保留,因此即使您直接在对象中分配它,相同的引用也可以在不同的位置。我不知道这些情况的 StyleCop 规则,但我对 StyleCop 或 FxCop 可用的内容没有很好的概述,因此很可能有一些东西可以检查这些情况。我只会检查非字符串且不直接在任何属性或方法中返回的私有成员的同步情况。
Basically, you should not lock on any external object unless this is specifically a locking object (such as the
SyncRoot
property on the non-genericICollection
was designed for). Doing so carries the risk of other "users" of the reference also locking on it, leading to unwanted locking or even deadlocks.Obvisously,
this
andtypeof()
are by definition external objects. Strings are immutable and string literals are all interned, so that the same reference can be in unse at different places even if you directly assigned it in your object.I don't know of a StyleCop rule for those, but I don't have a good overview of what is available for StyleCop or FxCop, so there could very well be something in the wild to check for those cases. I'd check for synching only on private members which are not strings and not directly returned in any property or method.