What is Interlocked In .NET?

Leave a Comment

In multithreaded applications, multiple threads can access and modify shared variables concurrently. This can lead to race conditions. The System.Threading.Interlocked class provides atomic operations on variables, ensuring thread safety without using locks.


Common Use Cases

  • Counters (Increment/Decrement)
  • Flags (Boolean states)
  • Exchange operations
  • Compare-and-swap (CAS)

Why Use Interlocked?

  • Atomic operations: Guaranteed to complete without interruption
  • Lightweight: Faster than locking mechanisms
  • Lock-free: Reduces the chance of deadlocks

Thread-Safe Counter Example
using System;
using System.Threading;

class Program
{
    private static int counter = 0;

    static void Main()
    {
        Thread[] threads = new Thread[10];

        for (int i = 0; i < threads.Length; i++)
        {
            threads[i] = new Thread(() =>
            {
                for (int j = 0; j < 1000; j++)
                {
                    Interlocked.Increment(ref counter);
                }
            });
            threads[i].Start();
        }

        foreach (var t in threads) t.Join();

        Console.WriteLine($"Final counter value: {counter}");
    }
}


Methods in Interlocked

  • Interlocked.Increment(ref int location)
  • Interlocked.Decrement(ref int location)
  • Interlocked.Add(ref int location, int value)
  • Interlocked.Exchange(ref T location, T value)
  • Interlocked.CompareExchange(ref T location, T value, T comparand)

Thread-Safe Flag Example (Boolean)
Booleans aren't directly supported by Interlocked, but you can simulate them using integers:
private static int isRunning = 0;

if (Interlocked.CompareExchange(ref isRunning, 1, 0) == 0)
{
    try
    {
        // Do work
    }
    finally
    {
        Interlocked.Exchange(ref isRunning, 0);
    }
}


Summary
Interlocked is ideal for low-level concurrency control. Best for simple shared variable updates. Use it when you want lock-free synchronization. For complex data structures, prefer lock or concurrent collections.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Previous PostOlder Post Home

0 comments:

Post a Comment