title: How should I increment a number for a round robin threading scenario with least contention?
body: <p>If many threads are calling <code>GetNextNumber</code> simultaneously with the following code, <code>GetNextNumber</code> will return 1 more times than any other numbers.</p>
  
  <pre><code>private class RoundRobbinNumber
  {
      private int _maxNumbers = 10;
      private int _lastNumber;
  
      private RoundRobbinNumber(int maxNumbers)
      {
          _maxNumbers = maxNumbers;
      }
  
      public int GetNextNumber()
      {
          int nextNumber = Interlocked.Increment(ref _lastNumber);
          if (_lastNumber &gt; _maxNumbers)
          {
              Interlocked.CompareExchange(ref _lastNumber, 1, _maxNumbers);
              nextNumber = 1;
          }
          return nextNumber;
      }
  }
  </code></pre>
  
  <p>Is there a way to reset the <code>_lastNumber</code> back to one, and reliably return an incremented number for each thread calling <code>GetNextNumber()</code>, without having to use a lock?</p>