C# Thread safe fast(est) counter

北战南征 提交于 2019-11-29 20:54:21

This would be simpler:

return Interlocked.Increment(ref COUNTER);

MSDN Interlocked.Increment

Les

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!