| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="Suspender.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Collections.Generic; |
| | | 9 | | |
| | | 10 | | namespace MyNet.Utilities.Suspending; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// Provides an implementation of the <see cref="ISuspender"/> interface, allowing operations to be suspended and resume |
| | | 14 | | /// </summary> |
| | | 15 | | public class Suspender : ISuspender |
| | | 16 | | { |
| | 2490 | 17 | | private readonly Stack<SuspendScope> _scopes = new(); |
| | | 18 | | |
| | | 19 | | /// <inheritdoc/> |
| | 6672 | 20 | | public bool IsSuspended => _scopes.TryPeek(out var scope) && scope.IsSuspended; |
| | | 21 | | |
| | | 22 | | /// <inheritdoc/> |
| | 69 | 23 | | public IDisposable Suspend() => new SuspendScope(this, true); |
| | | 24 | | |
| | | 25 | | /// <inheritdoc/> |
| | 12 | 26 | | public IDisposable Resume() => new SuspendScope(this, false); |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Pushes a new suspend scope onto the stack. This method is called by the <see cref="SuspendScope"/> constructor t |
| | | 30 | | /// </summary> |
| | | 31 | | /// <param name="scope">The suspend scope to push onto the stack.</param> |
| | 81 | 32 | | internal void Push(SuspendScope scope) => _scopes.Push(scope); |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Pops the specified suspend scope from the stack. This method is called by the <see cref="SuspendScope"/> Dispose |
| | | 36 | | /// </summary> |
| | | 37 | | /// <param name="scope">The suspend scope to pop from the stack.</param> |
| | | 38 | | /// <exception cref="InvalidOperationException">Thrown if the scopes are not disposed in the correct order.</excepti |
| | | 39 | | internal void Pop(SuspendScope scope) |
| | | 40 | | { |
| | 84 | 41 | | if (!_scopes.TryPeek(out var current) || !ReferenceEquals(current, scope)) |
| | 3 | 42 | | throw new InvalidOperationException("Suspend scopes must be disposed in reverse order."); |
| | | 43 | | |
| | 81 | 44 | | _scopes.Pop(); |
| | 81 | 45 | | } |
| | | 46 | | } |
| | | 47 | | |