Please let me know if you see any performance improvements, bugs, or anything you'd change and why.    public static bool TrySpeculativeUpdate(ref int field, out int result,        Func<int, int> update, Func<int, bool> shouldAbort)    {        SpinWait spinWait = new SpinWait();        while (true)        {            int snapshot = field;            if (shouldAbort(field))            {                result = 0;                return false;            }            else            {                int calc = update(snapshot);                if (Interlocked.CompareExchange(ref field, calc, snapshot) == snapshot)                {                    result = calc;                    return true;                }            }            spinWait.SpinOnce();        }    }Can be used like this    private bool TryIncreaseCapacity(out int newCapacity)    {        return TrySpeculativeUpdate(ref _currentCapacity, out newCapacity,            (currentCapacity) => currentCapacity + 1,            (currentCapacity) => currentCapacity == _maxCapacity);    }    if (this.TryIncreaseCapacity(out newCapacity))    {        ...    }    else    {        ...    }What I'm really trying to accomplish is the fastest thread safe version of Interlocked.Increment that will stop incrementing at a max value and I will have some way of detecting it stopped incrementing.
Try a speculative, concurrent, lock free, atomic update until abort condition matches
c#;.net;concurrency