This rule raises an issue when a private field used in a lock statement is declared with type object instead of System.Threading.Lock, and its other uses allow a safe conversion.

This applies to projects using C# 13 or later, targeting .NET 9 or later, where System.Threading.Lock is available.

Why is this an issue?

When using the lock statement in C#, you need an object to serve as the synchronization point. Traditionally, developers have used private readonly object _lock = new(); for this purpose.

Starting with C# 13 and .NET 9, Microsoft introduced System.Threading.Lock as a dedicated type specifically designed for use with lock statements. This new type offers two advantages:

Continuing to use object for lock fields means missing out on these benefits, especially in performance-critical code sections.

Exceptions

This rule only raises an issue when it can prove that converting the field to Lock is safe everywhere the field is used. It stays silent whenever that cannot be guaranteed, for example when the field is accessible outside its declaring type, used for something other than locking, locked by a lock statement whose body contains a yield statement, or locked anywhere inside an async method.

How to fix it

Change the field declaration from object to System.Threading.Lock. All existing lock statements using the field continue to work without modification. If the field is initialized or reassigned with a new object, change those creations to Lock as well.

Code examples

Noncompliant code example

public sealed class ExampleDataStructure
{
    readonly object _lockObj = new(); // Noncompliant

    public void Modify()
    {
        lock (_lockObj)
        {
            // Critical section associated with _lockObj
        }
    }
}

Compliant solution

public sealed class ExampleDataStructure
{
    readonly Lock _lockObj = new();

    public void Modify()
    {
        lock (_lockObj)
        {
            // Critical section associated with _lockObj
        }
    }
}

Resources

Documentation