| | | 1 | | namespace NexusLabs.Needlr.AgentFramework.Progress; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Composite <see cref="IDisposable"/> that owns a fixed set of child disposables |
| | | 5 | | /// and releases them in reverse order on <see cref="Dispose"/>. |
| | | 6 | | /// </summary> |
| | | 7 | | /// <remarks> |
| | | 8 | | /// <para> |
| | | 9 | | /// Null entries are ignored, allowing callers to mix typed references with |
| | | 10 | | /// conditional <c>as IDisposable</c> casts without pre-filtering. All entries |
| | | 11 | | /// are disposed even if earlier ones throw; collected exceptions are re-thrown |
| | | 12 | | /// as a single <see cref="AggregateException"/>. |
| | | 13 | | /// </para> |
| | | 14 | | /// <para> |
| | | 15 | | /// Used primarily by the source generator's <c>BeginXxxAgentProgressScope</c> |
| | | 16 | | /// emission to tie the lifetime of per-scope sinks (that implement |
| | | 17 | | /// <see cref="IDisposable"/>) to the returned scope handle, preventing leaks. |
| | | 18 | | /// </para> |
| | | 19 | | /// </remarks> |
| | | 20 | | public sealed class CompositeDisposable : IDisposable |
| | | 21 | | { |
| | | 22 | | private readonly IDisposable?[] _disposables; |
| | | 23 | | private bool _disposed; |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Creates a composite wrapping the supplied disposables in order. |
| | | 27 | | /// </summary> |
| | 0 | 28 | | public CompositeDisposable(IEnumerable<IDisposable?> disposables) |
| | | 29 | | { |
| | 0 | 30 | | ArgumentNullException.ThrowIfNull(disposables); |
| | 0 | 31 | | _disposables = disposables.ToArray(); |
| | 0 | 32 | | } |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Creates a composite wrapping the supplied disposables in order. |
| | | 36 | | /// </summary> |
| | 4 | 37 | | public CompositeDisposable(params IDisposable?[] disposables) |
| | | 38 | | { |
| | 4 | 39 | | ArgumentNullException.ThrowIfNull(disposables); |
| | 4 | 40 | | _disposables = disposables; |
| | 4 | 41 | | } |
| | | 42 | | |
| | | 43 | | /// <inheritdoc /> |
| | | 44 | | public void Dispose() |
| | | 45 | | { |
| | 6 | 46 | | if (_disposed) return; |
| | 4 | 47 | | _disposed = true; |
| | | 48 | | |
| | 4 | 49 | | List<Exception>? errors = null; |
| | 28 | 50 | | for (int i = _disposables.Length - 1; i >= 0; i--) |
| | | 51 | | { |
| | | 52 | | try |
| | | 53 | | { |
| | 10 | 54 | | _disposables[i]?.Dispose(); |
| | 9 | 55 | | } |
| | 1 | 56 | | catch (Exception ex) |
| | | 57 | | { |
| | 1 | 58 | | errors ??= new List<Exception>(); |
| | 1 | 59 | | errors.Add(ex); |
| | 1 | 60 | | } |
| | | 61 | | } |
| | | 62 | | |
| | 4 | 63 | | if (errors is not null) |
| | 1 | 64 | | throw new AggregateException(errors); |
| | 3 | 65 | | } |
| | | 66 | | } |