Combining Interlocked.Increment and Interlocked.Exchange

前端 未结 1 1385
谎友^
谎友^ 2021-01-21 15:37

I wish to atomically increment a static variable and simultaneously assign the new value to an instance field in a lock-free manner. The objective is for each object to get a un

相关标签:
1条回答
  • You only need to do this:

    orderingId = Interlocked.Increment(ref currentOrderingId);
    

    There's no way that two threads could then receive the same value, so it is threadsafe.

    0 讨论(0)
提交回复
热议问题