CodeQL documentation

Locking the ‘this’ object in a lock statement

ID: cs/lock-this
Kind: problem
Severity: warning
Precision: high
Tags:
   - reliability
   - maintainability
   - modularity
   - external/cwe/cwe-662
Query suites:
   - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

It is inadvisable to use this in a lock statement, because other classes could also attempt to lock the object, resulting in inefficiency or deadlock.

Recommendation

Create a private readonly Object which is used exclusively for locking. This ensures that no other classes can use the same lock.

Example

The following example uses a private readonly variable called mutex to use in the lock statement.

class ThreadSafe
{
    private readonly Object mutex = new Object();

    int value = 0;

    public void Inc()
    {
        lock (mutex)   // Correct
        {
            ++value;
        }
    }
}

References