protected void EnsureAccessible()
 {
     if (CheckAccessible && this.ReferenceCount == 0)
     {
         ThrowHelper.ThrowIllegalReferenceCountException(0);
     }
 }
        private void RetainSlow(int increment, int refCnt)
        {
            int oldRefCnt;

            do
            {
                oldRefCnt = refCnt;
                int nextCnt = refCnt + increment;

                // Ensure we not resurrect (which means the refCnt was 0) and also that we encountered an overflow.
                if (nextCnt <= increment)
                {
                    ThrowHelper.ThrowIllegalReferenceCountException(refCnt, increment);
                }

                refCnt = Interlocked.CompareExchange(ref _referenceCount, nextCnt, refCnt);
            } while (refCnt != oldRefCnt);
        }
        int ReleaseSlow(int decrement, int refCnt)
        {
            int oldRefCnt;

            do
            {
                oldRefCnt = refCnt;

                if (refCnt < decrement)
                {
                    ThrowHelper.ThrowIllegalReferenceCountException(refCnt, -decrement);
                }

                refCnt = Interlocked.CompareExchange(ref _referenceCount, refCnt - decrement, refCnt);
            } while (refCnt != oldRefCnt);

            return(refCnt);
        }
        IReferenceCounted Retain0(int increment)
        {
            int currRefCnt = Volatile.Read(ref _referenceCount);

            int nextCnt = currRefCnt + increment;

            // Ensure we not resurrect (which means the refCnt was 0) and also that we encountered an overflow.
            if (nextCnt <= increment)
            {
                ThrowHelper.ThrowIllegalReferenceCountException(currRefCnt, increment);
            }

            var refCnt = Interlocked.CompareExchange(ref _referenceCount, nextCnt, currRefCnt);

            if (currRefCnt != refCnt)
            {
                RetainSlow(increment, refCnt);
            }

            return(this);
        }
        bool Release0(int decrement)
        {
            int currRefCnt = Volatile.Read(ref _referenceCount);

            if (currRefCnt < decrement)
            {
                ThrowHelper.ThrowIllegalReferenceCountException(currRefCnt, -decrement);
            }

            var refCnt = Interlocked.CompareExchange(ref _referenceCount, currRefCnt - decrement, currRefCnt);

            if (currRefCnt != refCnt)
            {
                refCnt = ReleaseSlow(decrement, refCnt);
            }

            if (refCnt == decrement)
            {
                Deallocate();
                return(true);
            }
            return(false);
        }