Search code examples
c#multithreadingthread-safetycounter

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

  • This would be simpler:

    return Interlocked.Increment(ref COUNTER);
    

    MSDN Interlocked.Increment