C# Thread safe fast(est) counter

What is the way to obtain a thread safe counter in C# with best possible performance?

This is as simple as it gets:

public static long GetNextValue()
{
    long result;
    lock (LOCK)
    {
        result = COUNTER++;
    }
    return result;
}

But are there faster alternatives?


Solution 1:

This would be simpler:

return Interlocked.Increment(ref COUNTER);

MSDN Interlocked.Increment

Solution 2:

As recommended by others, the Interlocked.Increment will have better performance than lock(). Just take a look at the IL and Assembly where you will see that Increment turns into a "bus lock" statement and its variable is directly incremented (x86) or "added" to (x64).

This "bus lock" statement locks the bus to prevent another CPU from accessing the bus while the calling CPU does its operation. Now, take a look at the C# lock() statement's IL. Here you will see calls to Monitor in order to begin or end a section.

In other words, .Net lock() statement is doing a lot more than the .Net Interlocked.Increment.

So, if all you want to do is increment a variable, Interlock.Increment will be faster. Review all of the Interlocked methods to see the various atomic operations available and to find those that suit your needs. Use lock() when you want to do more complex things like multiple inter-related increments/decrements, or to serialize access to resources that are more complex than integers.

Solution 3:

I suggest you use .NET's built in interlock increment in the System.Threading library.

The following code will increment a long variable by reference and is completely thread safe:

Interlocked.Increment(ref myNum);

Source: http://msdn.microsoft.com/en-us/library/dd78zt0c.aspx