C# Thread safe fast(est) counter

后端 未结 5 2026
攒了一身酷
攒了一身酷 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:09

    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

提交回复
热议问题