Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Thread safe fast(est) counter

People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

Apa yang dimaksud dengan huruf C?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).


This would be simpler:

return Interlocked.Increment(ref COUNTER);

MSDN Interlocked.Increment


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


Try with Interlocked.Increment