Alex Rivera | Logout

C# Thread safe fast(est) counter

Asked 2012-11-01T16:47:39.977
223

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?

Edit
Report

1 Answer

44

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

answered 2012-11-01T16:50:43.303

Your Answer