-4.8 C
New York
Thursday, January 9, 2025

The way to use the brand new Lock object in C# 13



First we’ll want to put in the BenchmarkDotNet NuGet bundle in our undertaking. Choose the undertaking within the Resolution Explorer window, then right-click and choose “Handle NuGet Packages.” Within the NuGet Package deal Supervisor window, seek for the BenchmarkDotNet bundle and set up it.

Alternatively, you may set up the bundle by way of the NuGet Package deal Supervisor console by working the command under.


dotnet add bundle BenchmarkDotNet

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


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 benchmark the efficiency of the 2 approaches, create a brand new C# class named NewLockKeywordBenchmark and enter the next code in there.



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles