C# - 如何检查缺少scope.Complete()语句?

Ben*_*aul 5 c# resharper qa ndepend

我团队中的程序员有时会打开一个事务而忘记包含scope.Complete()语句(参见下面的代码块).任何有关方法的想法

(1)搜索我们的解决方案是否缺少scope.Complete()语句,或

(2)让Visual Studio自动突出显示或发出缺少scope.Complete()语句的警告?

这是我们想念的那条线:

 using(TransactionScope scope = new TransactionScope())
 {
      /* Perform transactional work here */
      scope.Complete(); <-- we forget this line
      /* Optionally, include a return statement */
 }
Run Code Online (Sandbox Code Playgroud)

我试过的
 
尝试使用ReSharper自定义模式,没有运气.理想情况下,我会搜索类似的东西:

using(TransactionScope scope = new TransactionScope())
{
    $statements1$
    [^(scope.Complete();)]
    $statements2$
}
Run Code Online (Sandbox Code Playgroud)

但是,ReSharper只接受标识符的正则表达式,而不接受语句,因此这似乎不起作用(http://www.jetbrains.com/resharper/webhelp/Reference__Search_with_Pattern.html).

有任何想法吗?我也愿意使用其他插件或工具.

谢谢,

Pat*_*eam 3

NDepend 当然可以提供帮助,但无法 100% 检查您所要求的内容。NDepend 不知道方法体内部(方法调用的顺序)。因此,您最多可以在 LINQ (CQLinq) 上编写一个代码规则,该规则将检查方法是否正在创建TransactionScope,至少它必须调用TransactionScope.Complete()

warnif count > 0
from m in Application.Methods
where m.CreateA("System.Transactions.TransactionScope") &&
     !m.IsUsing("System.Transactions.TransactionScope.Complete()")
select m
Run Code Online (Sandbox Code Playgroud)

请注意,如果开发人员有足够的纪律来避免TransactionScope在一种方法中创建多个方法,那么此规则应该适合您。