Sunday, April 27, 2025

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



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

Alternatively, you’ll be able to set up the bundle through the NuGet Bundle 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 standard lock and the brand new strategy. To do that, change the Replace methodology you created earlier with two strategies, particularly, UpdateStockTraditional and UpdateStockNew, as proven within the code instance given under.


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

Stay Connected

0FansLike
3,912FollowersFollow
0SubscribersSubscribe
- Advertisement -spot_img

Latest Articles