Skip to content

New lock object C# 13.0concurrencyperformance

A new disposable System.Threading.Lock type optimized for modern lock statements.

The traditional lock statement used Monitor.Enter and Monitor.Exit for synchronization, which worked well but had limitations. It couldn't be used with using statements for more flexible scope control, and its implementation had room for performance improvements.

C# 13.0 introduces System.Threading.Lock, a new dedicated lock type designed specifically for the lock statement. It provides better performance, integrates with using for manual lock management, and offers a more modern API for thread synchronization.

Code

C#
using System.Threading;

class BankAccount
{
    private readonly Lock _balanceLock = new();
    private decimal _balance;

    public void Deposit(decimal amount)
    {
        lock (_balanceLock)
        {
            _balance += amount;
        }
    }

    // Can also use with using for manual control
    public void Transfer(decimal amount)
    {
        using (_balanceLock.EnterScope())
        {
            _balance -= amount;
            // Lock automatically released when scope exits
        }
    }
}
C#
class BankAccount
{
    private readonly object _balanceLock = new();
    private decimal _balance;

    public void Deposit(decimal amount)
    {
        lock (_balanceLock)
        {
            _balance += amount;
        }
    }

    // Manual Monitor usage for complex scenarios
    public void Transfer(decimal amount)
    {
        bool lockTaken = false;
        try
        {
            Monitor.Enter(_balanceLock, ref lockTaken);
            _balance -= amount;
        }
        finally
        {
            if (lockTaken)
                Monitor.Exit(_balanceLock);
        }
    }
}

Notes

  • The new Lock type is specifically designed for high-performance locking scenarios
  • Using lock with a Lock object uses its optimized EnterScope() method instead of Monitor
  • EnterScope() returns a disposable Scope struct that releases the lock when disposed
  • The Lock object provides better performance than Monitor in many scenarios
  • Traditional lock statements with other object types (like object, string) continue to use Monitor
  • Prefer Lock for new code; existing code using object locks continues to work unchanged

More information