Rule Definition
Software featuring inconsistent locking discipline incurs the risk of deadlock.
Locking on this or public members is a bad practice because it means the class loses control over the lock. Any other class could use the instance or the public member for synchronization, and impair scalability (best case) or create deadlocks (worst case).
Remediation
Review and refactor the source code.
Violation Code Sample
class Account
{
decimal balance;
public void Withdraw(decimal amount)
{
lock (this)
{
if (amount > balance)
{
throw new Exception("Insufficient funds");
}
balance -= amount;
}
}
}
Fixed Code Sample
public class Account { private readonly object balanceLock = new object(); private decimal balance; public Account(decimal initialBalance) { balance = initialBalance; } public decimal Debit(decimal amount) { lock (balanceLock) { if (balance >= amount) { Console.WriteLine($"Balance before debit :{balance, 5}"); Console.WriteLine($"Amount to remove :{amount, 5}"); balance = balance - amount; Console.WriteLine($"Balance after debit :{balance, 5}"); return amount; } else { return 0; } } } }
Reference
https://docs.microsoft.com/fr-fr/dotnet/csharp/language-reference/keywords/lock-statement
CISQ - ASCSMCWE667
Related Technologies
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.