| | | 1 | | using Elsa.Workflows.Models; |
| | | 2 | | using JetBrains.Annotations; |
| | | 3 | | |
| | | 4 | | namespace Elsa.Workflows; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// A LIFO stack based activity scheduler. |
| | | 8 | | /// </summary> |
| | | 9 | | [PublicAPI] |
| | | 10 | | public class StackBasedActivityScheduler : IActivityScheduler |
| | | 11 | | { |
| | 5 | 12 | | private readonly Stack<ActivityWorkItem> _stack = new(); |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | 15 | 15 | | public bool HasAny => _stack.Any(); |
| | | 16 | | |
| | | 17 | | /// <inheritdoc /> |
| | 15 | 18 | | public void Schedule(ActivityWorkItem activity) => _stack.Push(activity); |
| | | 19 | | |
| | | 20 | | /// <inheritdoc /> |
| | 10 | 21 | | public ActivityWorkItem Take() => _stack.Pop(); |
| | | 22 | | |
| | | 23 | | /// <inheritdoc /> |
| | 0 | 24 | | public IEnumerable<ActivityWorkItem> List() => _stack.ToList(); |
| | | 25 | | |
| | | 26 | | /// <inheritdoc /> |
| | 0 | 27 | | public bool Any(Func<ActivityWorkItem, bool> predicate) => _stack.Any(predicate); |
| | | 28 | | |
| | | 29 | | /// <inheritdoc /> |
| | 0 | 30 | | public ActivityWorkItem? Find(Func<ActivityWorkItem, bool> predicate) => _stack.FirstOrDefault(predicate); |
| | | 31 | | |
| | | 32 | | /// <inheritdoc /> |
| | | 33 | | public int RemoveWhere(Func<ActivityWorkItem, bool> predicate) |
| | | 34 | | { |
| | | 35 | | // The stack enumerates top-first, so what survives has to be pushed back in reverse to keep the same top. |
| | 13 | 36 | | var remaining = _stack.Where(x => !predicate(x)).ToList(); |
| | 3 | 37 | | var removedCount = _stack.Count - remaining.Count; |
| | | 38 | | |
| | 3 | 39 | | if (removedCount == 0) |
| | 1 | 40 | | return 0; |
| | | 41 | | |
| | 2 | 42 | | _stack.Clear(); |
| | | 43 | | |
| | 8 | 44 | | for (var i = remaining.Count - 1; i >= 0; i--) |
| | 2 | 45 | | _stack.Push(remaining[i]); |
| | | 46 | | |
| | 2 | 47 | | return removedCount; |
| | | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <inheritdoc /> |
| | 0 | 51 | | public void Clear() => _stack.Clear(); |
| | | 52 | | } |