1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
5 using System.Diagnostics;
7 namespace System.Threading
10 /// Provides callbacks to objects whose lifetime is managed by <see cref="DeferredDisposableLifetime{T}"/>.
12 internal interface IDeferredDisposable
15 /// Called when the object's refcount reaches zero.
17 /// <param name="disposed">
18 /// Indicates whether the object has been disposed.
21 /// If the refount reaches zero before the object is disposed, this method will be called with
22 /// <paramref name="disposed"/> set to false. If the object is then disposed, this method will be
23 /// called again, with <paramref name="disposed"/> set to true. If the refcount reaches zero
24 /// after the object has already been disposed, this will be called a single time, with
25 /// <paramref name="disposed"/> set to true.
27 void OnFinalRelease(bool disposed);
31 /// Manages the lifetime of an object which implements IDisposable, but which must defer the actual
32 /// cleanup of state until all existing uses of the object are complete.
34 /// <typeparam name="T">The type of object whose lifetime will be managed.</typeparam>
36 /// This type maintains a reference count, and tracks whether the object has been disposed. When
37 /// Callbacks are made to <see cref="IDeferredDisposable.OnFinalRelease(bool)"/> when the refcount
38 /// reaches zero. Objects that need to defer cleanup until they have been disposed *and* they have
39 /// no more references can do so in <see cref="IDeferredDisposable.OnFinalRelease(bool)"/> when
40 /// 'disposed' is true.
42 internal struct DeferredDisposableLifetime<T> where T : class, IDeferredDisposable
45 // _count is positive until Dispose is called, after which it's (-1 - refcount).
49 public bool AddRef(T obj)
53 int oldCount = Volatile.Read(ref _count);
55 // Have we been disposed?
57 throw new ObjectDisposedException(typeof(T).ToString());
59 int newCount = checked(oldCount + 1);
61 if (Interlocked.CompareExchange(ref _count, newCount, oldCount) == oldCount)
66 public void Release(T obj)
70 int oldCount = Volatile.Read(ref _count);
73 // We haven't been disposed. Decrement _count.
74 int newCount = oldCount - 1;
75 if (Interlocked.CompareExchange(ref _count, newCount, oldCount) == oldCount)
78 obj.OnFinalRelease(disposed: false);
84 Debug.Assert(oldCount != 0 && oldCount != -1);
86 // We've been disposed. Increment _count.
87 int newCount = oldCount + 1;
88 if (Interlocked.CompareExchange(ref _count, newCount, oldCount) == oldCount)
91 obj.OnFinalRelease(disposed: true);
98 public void Dispose(T obj)
102 int oldCount = Volatile.Read(ref _count);
104 return; // already disposed
106 int newCount = -1 - oldCount;
107 if (Interlocked.CompareExchange(ref _count, newCount, oldCount) == oldCount)
110 obj.OnFinalRelease(disposed: true);