0.7 C
New York
Monday, January 13, 2025

How you can use the brand new Lock object in C# 13



First we might want to set up the BenchmarkDotNet NuGet package deal in our undertaking. Choose the undertaking within the Answer Explorer window, then right-click and choose “Handle NuGet Packages”. Within the NuGet Package deal Supervisor window, discover the BenchmarkDotNet package deal and set up it.

Alternatively, you may set up the package deal by the NuGet Package deal Supervisor console by working the next command.


dotnet add package deal BenchmarkDotNet

Subsequent, for our efficiency comparability, we’ll replace the Inventory class to incorporate each a standard lock and the brand new strategy. To do that, exchange the replace technique you created earlier with two strategies, particularly UpdateStockTraditional and UpdateStockNew, as proven within the code instance beneath.


public class Inventory
{
    personal readonly Lock _lockObjectNewApproach = new();
    personal readonly object _lockObjectTraditionalApproach = new();
    personal int _itemsInStockTraditional = 0;
    personal 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)
    {
        utilizing (_lockObjectNewApproach.EnterScope())
        {
            if (flag)
                _itemsInStockNew += numberOfItems;
            else
                _itemsInStockNew -= numberOfItems;
        }
    }
}

Now, to check the efficiency of the 2 approaches, create a brand new C# class named NewLockKeywordBenchmark and enter the next code there.

Related Articles

Latest Articles