C# Thread safe fast(est) counter

JohnDoDo picture JohnDoDo · Nov 1, 2012 · Viewed 84.4k times · Source

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?

Answer

Austin Salonen picture Austin Salonen · Nov 1, 2012

This would be simpler:

return Interlocked.Increment(ref COUNTER);

MSDN Interlocked.Increment