First we’ll want to put in 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, seek for the BenchmarkDotNet package deal and set up it.
Alternatively, you possibly can set up the package deal through the NuGet Package deal 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, exchange the Replace methodology you created earlier with two strategies, specifically, UpdateStockTraditional and UpdateStockNew, as proven within the code instance given 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 benchmark the efficiency of the 2 approaches, create a brand new C# class named NewLockKeywordBenchmark and enter the next code in there.