30-Day .NET Challenge - Day 17: What Is the Interlocked Class Tool?

Written by ssukhpinder | Published 2024/04/07
Tech Story Tags: dotnet | aspnetcore | coding | software-development | c-sharp | .net-challenge | interlocked-class-tool | hackernoon-top-story | hackernoon-es | hackernoon-hi | hackernoon-zh | hackernoon-fr | hackernoon-bn | hackernoon-ru | hackernoon-vi | hackernoon-pt | hackernoon-ja | hackernoon-de | hackernoon-ko | hackernoon-tr

TLDRUsing traditional locking techniques can sometimes cause performance bottlenecks for atomic operations. The.Net provide a powerful tool called the “Interlocked” class for all atomic operations through which developers can reduce contention and improve the performance of the application. The 30 Day.Net Challenge challenges developers to learn how to use Interlocked classes.via the TL;DR App

The .Net provides a powerful tool called the “Interlocked” class for all atomic operations through which developers can reduce contention and improve the performance of the application.

Introduction

In multi-threaded application scenarios, using traditional locking techniques can sometimes cause performance bottlenecks for atomic operations. The .Net provides a powerful tool called the “Interlocked” class for all atomic operations through which developers can reduce contention and improve the performance of the application.

Learning Objectives

  • Problem with locks
  • Using Interlocked classes

Prerequisites for Developers

  • Basic understanding of C# programming language

30 Day .Net Challenge

Getting Started

Understanding the Problem With Locks

Traditionally, to ensure thread safety when multiple threads access a shared resource, developers use locks. Locking prevents multiple threads from entering a critical section of code simultaneously, thus, ensuring that only one thread at a time can modify the shared resource.

    private int _counter;
    private readonly object _syncRoot = new object();
    
    public void IncrementCounter()
    {
        lock (_syncRoot)
        {
            _counter++;
        }
    }

The aforementioned approach introduces a risk of potential performance issue called contention wherein when multiple threads try to access the lock simultaneously, they are put on hold except for the one that successfully gets the lock.

The Interlocked Class: A Better Way

The .NET framework offers the Interlocked class as a part of the System.Threading namespace, designed to perform atomic operations efficiently. Atomic operations are indivisible; they complete entirely without interruption.

    private int _counter;
    
    public void IncrementCounter()
    {
        Interlocked.Increment(ref _counter);
    }

As the Interlocked class does not require locks, it solves the issue of contention as mentioned in the traditional approach.

Complete Example

Add a new class name IncrementClass, and add the following code snippet

    
    public static class IncrementClass
    {
        private static int _counter = 0;
    
        /// <summary>
        /// Outputs
        /// Counter value: 10
        /// </summary>
        public static void TestIncrementCounter()
        {
            // Create an array to hold the tasks
            Task[] tasks = new Task[10];
    
            // Initialize and start tasks
            for (int i = 0; i < tasks.Length; i++)
            {
                tasks[i] = Task.Run(() => IncrementCounter());
            }
    
            // Wait for all tasks to complete
            Task.WaitAll(tasks);
    
            Console.WriteLine($"Counter value: {_counter}");
        }
    
        public static void IncrementCounter()
        {
            // Safely increment the counter across multiple threads
            Interlocked.Increment(ref _counter);
        }
    }

Call from the main method as follows:

    #region Day 17: Increment Class
    
    IncrementClass.TestIncrementCounter();
    
    #endregion

Console output:

    Counter value: 10

Complete Code on GitHub

GitHub — ssukhpinder/30DayChallenge.Net

C# Programming🚀

Thank you for being a part of the C# community! Before you leave:

Follow us: Youtube | X | LinkedIn | Dev.to Visit our other platforms: GitHub


Written by ssukhpinder | Programmer by heart | C# | Python | .Net Core | Xamarin | Angular | AWS
Published by HackerNoon on 2024/04/07