using System; using System.Threading; /// /// A minimal threadsafe counter. /// class AtomicCounter { /// /// The current value of the counter. /// int currentValue = 0; /// /// Increments the value of the counter. /// /// /// The amount to increment. /// If the counter would overflow. /// The new value of the counter. /// /// This method is threadsafe. public int Increment(int incrementBy = 1) { int oldValue, newValue; do { oldValue = currentValue; newValue = oldValue + incrementBy; if (newValue < 0) throw new OverflowException("Counter value is out of range"); } while (oldValue != Interlocked.CompareExchange(ref currentValue, newValue, oldValue)); return newValue; } }