C# Thread safe fast(est) counter

后端 未结 5 2025
攒了一身酷
攒了一身酷 2020-12-12 17:32

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()         


        
5条回答
  •  隐瞒了意图╮
    2020-12-12 18:28

    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.

提交回复
热议问题