Exemplo n.º 1
0
        private ReferenceCountedDisposable(T instance, BoxedReferenceCount referenceCount)
        {
            _instance = instance ?? throw new ArgumentNullException(nameof(instance));

            // The reference count has already been incremented for this instance
            _boxedReferenceCount = referenceCount;
        }
Exemplo n.º 2
0
        /// <summary>
        /// Provides the implementation for <see cref="TryAddReference"/> and
        /// <see cref="WeakReference.TryAddReference"/>.
        /// </summary>
        private static ReferenceCountedDisposable <T>?TryAddReferenceImpl(T?target, BoxedReferenceCount referenceCount)
        {
            lock (referenceCount)
            {
                if (referenceCount._referenceCount == 0)
                {
                    // The target is already disposed, and cannot be reused
                    return(null);
                }

                if (target == null)
                {
                    // The current reference has been disposed, so even though it isn't disposed yet we don't have a
                    // reference to the target
                    return(null);
                }

                checked
                {
                    referenceCount._referenceCount++;
                }

                // Must return a new instance, in order for the Dispose operation on each individual instance to
                // be idempotent.
                return(new ReferenceCountedDisposable <T>(target, referenceCount));
            }
        }