Locking the ‘this’ object in a lock statement¶
ID: cs/lock-thisKind: problemSecurity severity: Severity: warningPrecision: highTags: - quality - reliability - concurrency - modularity - external/cwe/cwe-662Query suites: - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
It is inadvisable to usethis in alock statement, because other classes could also attempt to lock the object, resulting in inefficiency or deadlock.
Recommendation¶
Create aprivatereadonlyObject which is used exclusively for locking. This ensures that no other classes can use the same lock.
Example¶
The following example uses aprivatereadonly variable calledmutex to use in thelock statement.
classThreadSafe{privatereadonlyObjectmutex=newObject();intvalue=0;publicvoidInc(){lock(mutex)// Correct{++value;}}}
References¶
MSDN, C# Reference:lock Statement.
Common Weakness Enumeration:CWE-662.