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 aLock
object uses its optimizedEnterScope()
method instead ofMonitor
EnterScope()
returns a disposableScope
struct that releases the lock when disposed- The
Lock
object provides better performance thanMonitor
in many scenarios - Traditional
lock
statements with other object types (likeobject
,string
) continue to useMonitor
- Prefer
Lock
for new code; existing code usingobject
locks continues to work unchanged