CodeQL documentation

Locking the ‘this’ object in a lock statement

ID: cs/lock-this
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - quality
   - reliability
   - concurrency
   - 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

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy