| | | 1 | | using System; |
| | | 2 | | using System.Threading; |
| | | 3 | | |
| | | 4 | | namespace SwiftCollections.Pool; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// A lease that wraps an object rented from an <see cref="ISwiftObjectPool{T}"/> and ensures it is automatically |
| | | 8 | | /// released back to the pool when disposed. Designed to simplify resource management and avoid manual release errors. |
| | | 9 | | /// </summary> |
| | | 10 | | /// <typeparam name="T">The type of the object being pooled. Must be a reference type.</typeparam> |
| | | 11 | | public sealed class SwiftPooledObject<T> : IDisposable where T : class |
| | | 12 | | { |
| | | 13 | | #region Fields |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// The rented object that will be returned to the pool upon disposal. |
| | | 17 | | /// </summary> |
| | | 18 | | private T _value; |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// The pool from which the object was rented. |
| | | 22 | | /// </summary> |
| | | 23 | | private ISwiftObjectPool<T> _pool; |
| | | 24 | | |
| | | 25 | | private int _disposed; |
| | | 26 | | |
| | | 27 | | #endregion |
| | | 28 | | |
| | | 29 | | #region Constructor |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Initializes a new instance of the <see cref="SwiftPooledObject{T}"/> class. |
| | | 33 | | /// </summary> |
| | | 34 | | /// <param name="value">The rented object.</param> |
| | | 35 | | /// <param name="pool">The pool that owns the object.</param> |
| | | 36 | | /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> or <paramref name="pool"/> is null.</ |
| | 7 | 37 | | internal SwiftPooledObject(T value, ISwiftObjectPool<T> pool) |
| | 7 | 38 | | { |
| | 7 | 39 | | SwiftThrowHelper.ThrowIfNull(value, nameof(value)); |
| | 6 | 40 | | SwiftThrowHelper.ThrowIfNull(pool, nameof(pool)); |
| | | 41 | | |
| | 5 | 42 | | _value = value; |
| | 5 | 43 | | _pool = pool; |
| | 5 | 44 | | } |
| | | 45 | | |
| | | 46 | | #endregion |
| | | 47 | | |
| | | 48 | | #region IDisposable Implementation |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// Releases the rented object back to its pool. |
| | | 52 | | /// </summary> |
| | | 53 | | /// <remarks> |
| | | 54 | | /// This method is automatically called when the <see cref="SwiftPooledObject{T}"/> goes out of scope in a |
| | | 55 | | /// using block or when manually disposed. |
| | | 56 | | /// </remarks> |
| | | 57 | | public void Dispose() |
| | 6 | 58 | | { |
| | 6 | 59 | | if (Interlocked.Exchange(ref _disposed, 1) != 0) |
| | 1 | 60 | | return; |
| | | 61 | | |
| | 5 | 62 | | ISwiftObjectPool<T> pool = _pool; |
| | 5 | 63 | | T value = _value; |
| | | 64 | | |
| | 5 | 65 | | _pool = null; |
| | 5 | 66 | | _value = null; |
| | | 67 | | |
| | 5 | 68 | | if (pool != null && value != null) |
| | 5 | 69 | | pool.Release(value); |
| | 6 | 70 | | } |
| | | 71 | | |
| | | 72 | | #endregion |
| | | 73 | | } |