Day 17 of 30-Day .NET Challenge: Interlocked Class
Tags: dotnet, csharp, programming, aspnet
Published: 2024-04-05 08:17:00

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.


## 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](https://singhsukhpinder.medium.com/list/52a751260fe1)

## 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.
```csharp
    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.
```csharp
    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
```csharp
    
    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
```csharp
    #region Day 17: Increment Class
    
    IncrementClass.TestIncrementCounter();
    
    #endregion
```
Console output
```
    Counter value: 10
```
## Complete Code on GitHub
[GitHub — ssukhpinder/30DayChallenge.Net](https://github.com/ssukhpinder/30DayChallenge.Net/tree/main)

### C# Programming🚀

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

Follow us: [Youtube](https://www.youtube.com/channel/UCejYGg4gAOa1uPAObFuk1HQ) | [X](https://twitter.com/sukhsukhpinder) | [LinkedIn](https://www.linkedin.com/in/sukhpinder-singh/) | [Dev.to](https://dev.to/ssukhpinder) 
Visit our other platforms: [GitHub](https://github.com/ssukhpinder) 
More content at [C# Programming](https://medium.com/c-sharp-progarmming)