How to use the new Lock object in C# 13
January 14, 2025

How to use the new Lock object in C# 13

First we need to install the BenchmarkDotNet NuGet package into our project. Select the project in the Solution Explorer window, then right-click and select Manage NuGet Packages. In the NuGet Package Manager window, locate the BenchmarkDotNet package and install it.

Alternatively, you can install the package through the NuGet Package Manager Console by running the command below.


dotnet add package BenchmarkDotNet

Next, to compare performance, we’ll update the Stock class to include both traditional locking and the new approach. To do this, replace the Update method you created earlier with two methods, namely UpdateStockTraditional and UpdateStockNew, as shown in the code example given below.


public class Stock
{
    private readonly Lock _lockObjectNewApproach = new();
    private readonly object _lockObjectTraditionalApproach = new();
    private int _itemsInStockTraditional = 0;
    private int _itemsInStockNew = 0;
    public void UpdateStockTraditional(int numberOfItems, bool flag = true)
    {
        lock (_lockObjectTraditionalApproach)
            {
                if (flag)
                _itemsInStockTraditional += numberOfItems;
                else
                _itemsInStockTraditional -= numberOfItems;
        }
    }
    public void UpdateStockNew(int numberOfItems, bool flag = true)
    {
        using (_lockObjectNewApproach.EnterScope())
        {
            if (flag)
                _itemsInStockNew += numberOfItems;
            else
                _itemsInStockNew -= numberOfItems;
        }
    }
}

Now, to evaluate the performance of the two approaches, create a new C# class called NewLockKeywordBenchmark and enter the following code there.

2025-01-09 09:00:00

Leave a Reply

Your email address will not be published. Required fields are marked *