Monitor TryEnter/Exit must be both called within the same method

Rule ND2502 .NET Framework Usage / System.Threading

Warns when System.Threading.Monitor Enter()/TryEnter() and Exit() are not called within the same method: harder to locate where critical sections begin and end, and complex error-prone scenarios.

How to fix

Refactor so Monitor critical sections begin and end in the same method. Use the C# lock keyword for basic scenarios; explicit Monitor only for advanced ones needing Wait() and Pulse(). More: http://www.codeproject.com/Articles/13453/Practical-NET-and-C-Chapter

CQLinq source

This rule is written in CQLinq, C# LINQ over the NDepend code model. It ships with every new NDepend project: you can read it, adapt it, or use it as a starting point for your own custom rules.

// <Name>Monitor TryEnter/Exit must be both called within the same method</Name>
// <Id>ND2502:MonitorTryEnterExitMustBeBothCalledWithinTheSameMethod</Id>

warnif count > 0 

let enterMethods = ThirdParty.Methods.WithFullNameWildcardMatchIn(
   "System.Threading.Monitor.Enter(*",
   "System.Threading.Monitor.TryEnter(*")

from m in Application.Methods.UsingAny(enterMethods) 
where
    !m.IsUsing ("System.Threading.Monitor.Exit(Object)".AllowNoMatch())
select new { 
   m, 
   enterMethodsCalled = m.MethodsCalled.Intersect(enterMethods),
   Debt = 15.ToMinutes().ToDebt(),
   Severity = Severity.High
}

//<Expl>
// The *{0}* calls *{1}* but doesn't call corresponding *Monitor.(Try)Exit()* method{1?:s}.
// Refactor the code so that a *critical section* is contained within a single method.
//</Expl>

//<Desc>
// Warns when **System.Threading.Monitor** *Enter()*/*TryEnter()* and
// *Exit()* are not called within the same method: harder to locate where
// **critical sections** begin and end, and complex error-prone scenarios.
//</Desc>

//<HowToFix>
// Refactor so *Monitor critical sections* begin and end in the same method.
// Use the C# **lock** keyword for basic scenarios; explicit *Monitor* only
// for advanced ones needing *Wait()* and *Pulse()*. More:
// http://www.codeproject.com/Articles/13453/Practical-NET-and-C-Chapter
//</HowToFix>

.NET Framework Usage / System.Threading: all 6 items