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.
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:
System.Threading.Lock is optimized for locking scenarios and can provide performance improvements over the
traditional object-based approachContinuing to use object for lock fields means missing out on these benefits, especially in performance-critical code sections.
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.
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.
public sealed class ExampleDataStructure
{
readonly object _lockObj = new(); // Noncompliant
public void Modify()
{
lock (_lockObj)
{
// Critical section associated with _lockObj
}
}
}
public sealed class ExampleDataStructure
{
readonly Lock _lockObj = new();
public void Modify()
{
lock (_lockObj)
{
// Critical section associated with _lockObj
}
}
}