Is there a .Net StyleCop rule which warns about lock(this), lock(typeof, lock(<string obj>, etc.?

删除回忆录丶 提交于 2019-12-21 17:23:37

问题


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.


回答1:


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 for lock(this)




回答2:


Basically, you should not lock on any external object unless this is specifically a locking object (such as the SyncRoot property on the non-generic ICollection 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 and typeof() 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.



来源:https://stackoverflow.com/questions/2945790/is-there-a-net-stylecop-rule-which-warns-about-lockthis-locktypeof-locks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!