Skip to Content
All posts

Understanding the Interlocked API in C#

2 min read ·  — #csharp-interview#senior#concurrency#lock#interlocked api

Understanding the Interlocked API in C#

Introduction

The Interlocked class in C# plays a pivotal role in the domain of concurrent programming, especially when it comes to atomic operations. Atomicity, a fundamental concept in multi-threaded environments, refers to operations that are completely executed without interruption. In simpler terms, when you use the Interlocked API, you're ensuring that the operation will be completed by one thread before another thread can access the variable. This is crucial in scenarios where multiple threads are reading and writing shared data, as it helps avoid race conditions and data corruption.

Key Functions of the Interlocked API

  1. Increment and Decrement: These methods atomically increase or decrease the value of an integer variable. They're often used in counters or loop variables shared across threads.

    Example: Maintaining a thread-safe count of active users in a web application.

    private static int activeUsers = 0;
    
    public static void UserLoggedIn()
    {
        Interlocked.Increment(ref activeUsers);
    }
    
    public static void UserLoggedOut()
    {
        Interlocked.Decrement(ref activeUsers);
    }
  2. Add: This method atomically adds a value to an integer variable. It's useful for summing up values in a concurrent environment.

    Example: Aggregating total sales in a multi-threaded sales application.

    private static int totalSales = 0;
    
    public static void RecordSale(int saleAmount)
    {
        Interlocked.Add(ref totalSales, saleAmount);
    }
  3. Exchange: This method atomically sets a variable to a new value and returns the original value. It's useful for safely swapping values.

    Example: Implementing a thread-safe update of a configuration setting.

    private static int configValue = 0;
    
    public static int UpdateConfigValue(int newValue)
    {
        return Interlocked.Exchange(ref configValue, newValue);
    }
  4. CompareExchange: This method conditionally sets a variable to a new value based on its current value. It's extremely useful for scenarios where you need to update a value only if it hasn't been changed by another thread.

    Example: Updating a shared resource only if it hasn’t been modified by another thread.

    private static int threshold = 10;
    
    public static void UpdateThreshold(int newThreshold)
    {
        int initialValue;
        do
        {
            initialValue = threshold;
        }
        while (
         Interlocked.CompareExchange(
              ref threshold, newThreshold, initialValue) != initialValue
         );
    }

Conclusion

The Interlocked API is a powerful tool in C#'s concurrent programming arsenal, providing atomic operations that are essential for maintaining data integrity across multiple threads. These methods are efficient and less error-prone compared to manual locking mechanisms. Understanding and utilizing the Interlocked API is vital for developers who are involved in designing and implementing multi-threaded applications where data consistency and performance are of paramount importance.