.NET 9.0 System.Threading.Lock

How does a Lock work?

Lock is a mechanism to protect multiple threads from accessing the same piece of code. This code is often a critical section in your module. Allowing concurrent access could lead to a number of potential issues including race conditions, dead locks and/or inconsistent data. Using a lock will allow for thread synchronization, there by restricting access to the critical section of your code.

With .NET 9 and C# 13, the only difference is the way the compiler works under the hood when the keyword lock is encountered.

  • lock uses System.Thread.Lock behind the scenes for better performance.
  • The Lock type will have to be specified explicitly.

Prior to .NET 9

    public class Account
    {
        private decimal _balance;
        private static readonly object LockObject = new object();
        public Account(decimal balance) 
        {
            _balance = balance;
        }

        public void Deposit(decimal amount)
        {
          lock(LockObject)
          {
            //Critical code
            _balance -= amount;
          }
        }
    }

With .NET 9

  • In order to use this new feature, instead of using object reference, use Lock.

        public class Account
        {
            private decimal _balance;
            private static readonly Lock LockObject = new();
            public Account(decimal balance) 
            {
                //Critical code
                _balance = balance;
            }
    
            public void Deposit(decimal amount)
            {
                lock (LockObject)
                {
                    _balance -= amount;
                }
            }
        }
    
  • When you use Lock object explicity the code will be lowered to the below IL C# code

        public void Deposit(decimal amount)
        {
          var scope = LockObject.EnterScope();
          try
          {
            _balance -= amount;
          }
          finally
          {
            scope.Dispose();
          }
        }
    

With .NET 9

Written by

Deepti

I'm Deepti Velusamy. I’m a software developer with a strong focus on backend API development (.NET) and extensive experience in AWS, terraform, micro services and containerization.