Saturday, June 28, 2025

Tips on how to use the brand new Lock object in C# 13

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

Alternatively, you’ll be able to set up the package deal through the NuGet Bundle Supervisor console by operating the command beneath.


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 method. To do that, change the Replace technique you created earlier with two strategies, particularly, UpdateStockTraditional and UpdateStockNew, as proven within the code instance given beneath.


public class Inventory
{
    non-public readonly Lock _lockObjectNewApproach = new();
    non-public readonly object _lockObjectTraditionalApproach = new();
    non-public int _itemsInStockTraditional = 0;
    non-public 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.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles

PHP Code Snippets Powered By : XYZScripts.com