Day 17 of 30-Day .NET Challenge: Interlocked Class

Day 17 of 30-Day .NET Challenge: Interlocked Class

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


Introduction

In multi-threaded application scenarios, using 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.

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 Interlocked class does not require locks so 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
Contribute to ssukhpinder/30DayChallenge.Net development by creating an account on GitHub.github.com


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
More content at C# Programming

Did you find this article valuable?

Support C# Programming by becoming a sponsor. Any amount is appreciated!