Static analysis tool to check locking before access to variable

血红的双手。 提交于 2019-12-21 05:04:28

问题


I know there are a quite a few static analysis tools for C# or .Net around. See this question for a good list of available tools. I have used some of those in the past and they have a good way of detecting problems.

I am currently looking for a way to automatically enforce some locking rules we have in our teams. For example I would like to enforce the following rules:

"Every public method that uses member foo must acquire a lock on bar" Or "Every call to foobar event must be outside lock to bar"

Writing custom FxCop rules, if feasible, seems rather complex. Is there any simpler way of doing it?


回答1:


Multithreading is hard. Using locks is not the only way to make operations thread-safe. A developer may use non-blocking synchronization with a loop and Interlocked.CompareExchange, or some other mechanism instead. A rule can not determine if something is thread-safe.

If the purpose of rules is to ensure high quality code, I think the best way to go about this is to create a thread-safe version of your class which is simple to consume. Put checks in place that the more-complex synchronization code is only modified under code review by developers that understand multithreading.




回答2:


With NDepend you could write a code rule over a LINQ query (CQLinq) that could look like:

warnif count > 0 from m in Methods where
 m.IsUsing ("YourNamespace.YourClass.foo") && ( 
   ! m.IsUsing ("YourNamespace.YourClass.bar") ||
   ! m.IsUsing ("System.Threading.Monitor.Enter(Object)".AllowNoMatch()) ||
   ! m.IsUsing ("System.Threading.Monitor.Exit(Object)".AllowNoMatch()) )
select new { m, m.NbLinesOfCode }

Basically it will matches methods that uses the field foo, without using the field bar, or without calling Monitor Enter or Exit. This is not exactly what you are asking for, since you want lock explicitely on bar, but this is simple and quite close.

Notes that you can also write...

m.AssignField("YourNamespace.YourClass.foo")

... to restrict a specific write/assign field usage on foo.




回答3:


One of possible solutions could be implementation of Code Contracts. You define rules, run them at compile time (so can be also integrated in your CI environment if any) and get results.

For en example of using CodeContracts like a tool for code static analys see :

Static Code Analysis and Code Contracts



来源:https://stackoverflow.com/questions/9468601/static-analysis-tool-to-check-locking-before-access-to-variable

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