| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="SingleTaskRunner.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Threading; |
| | | 9 | | using System.Threading.Tasks; |
| | | 10 | | using Microsoft.Extensions.Logging; |
| | | 11 | | using MyNet.Utilities.Logging; |
| | | 12 | | |
| | | 13 | | namespace MyNet.Utilities.Threading; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Provides a mechanism to run a single instance of an asynchronous task at a time, with support for cancellation and n |
| | | 17 | | /// </summary> |
| | | 18 | | /// <param name="action">The asynchronous action to execute.</param> |
| | | 19 | | /// <param name="onRunningChanged">An optional callback invoked when the running state changes.</param> |
| | | 20 | | /// <param name="onCancelled">An optional callback invoked when the task is canceled.</param> |
| | | 21 | | /// <param name="logger">An optional logger for logging errors.</param> |
| | | 22 | | public sealed class SingleTaskRunner( |
| | | 23 | | Func<CancellationToken, Task> action, |
| | | 24 | | Action<bool>? onRunningChanged = null, |
| | | 25 | | Action? onCancelled = null, |
| | | 26 | | ILogger? logger = null) |
| | | 27 | | : IDisposable |
| | | 28 | | { |
| | 30 | 29 | | private readonly Lock _lock = new(); |
| | 30 | 30 | | private readonly Func<CancellationToken, Task> _action = action ?? throw new ArgumentNullException(nameof(action)); |
| | | 31 | | private CancellationTokenSource? _cts; |
| | | 32 | | private Task? _currentTask; |
| | | 33 | | private bool _isRunning; |
| | | 34 | | private bool _disposed; |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// Gets a value indicating whether a task is currently running. |
| | | 38 | | /// </summary> |
| | | 39 | | public bool IsRunning |
| | | 40 | | { |
| | | 41 | | get |
| | 21 | 42 | | { |
| | | 43 | | lock (_lock) |
| | | 44 | | { |
| | 21 | 45 | | return _isRunning; |
| | | 46 | | } |
| | 21 | 47 | | } |
| | | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// Gets the currently running task if any. |
| | | 52 | | /// </summary> |
| | | 53 | | public Task? CurrentTask |
| | | 54 | | { |
| | | 55 | | get |
| | 27 | 56 | | { |
| | | 57 | | lock (_lock) |
| | | 58 | | { |
| | 27 | 59 | | return _currentTask; |
| | | 60 | | } |
| | 27 | 61 | | } |
| | | 62 | | } |
| | | 63 | | |
| | | 64 | | /// <summary> |
| | | 65 | | /// Starts execution if no task is already running. |
| | | 66 | | /// </summary> |
| | | 67 | | /// <returns> |
| | | 68 | | /// True if the task was started; otherwise false. |
| | | 69 | | /// </returns> |
| | | 70 | | public bool Run() |
| | 36 | 71 | | { |
| | | 72 | | lock (_lock) |
| | | 73 | | { |
| | 36 | 74 | | ObjectDisposedException.ThrowIf(_disposed, this); |
| | | 75 | | |
| | 33 | 76 | | if (_isRunning) |
| | 6 | 77 | | return false; |
| | | 78 | | |
| | 27 | 79 | | _cts?.Dispose(); |
| | | 80 | | |
| | 27 | 81 | | _cts = new(); |
| | 27 | 82 | | var token = _cts.Token; |
| | | 83 | | |
| | 27 | 84 | | _isRunning = true; |
| | | 85 | | |
| | 27 | 86 | | _currentTask = ExecuteAsync(token); |
| | 27 | 87 | | } |
| | | 88 | | |
| | 27 | 89 | | NotifyRunningChanged(true); |
| | | 90 | | |
| | 27 | 91 | | return true; |
| | 6 | 92 | | } |
| | | 93 | | |
| | | 94 | | /// <summary> |
| | | 95 | | /// Starts execution if no task is already running and returns the running task. |
| | | 96 | | /// </summary> |
| | | 97 | | /// <returns> |
| | | 98 | | /// The running task, or null if another execution is already in progress. |
| | | 99 | | /// </returns> |
| | 21 | 100 | | public Task? RunAsync() => Run() ? CurrentTask : null; |
| | | 101 | | |
| | | 102 | | /// <summary> |
| | | 103 | | /// Cancels the current execution. |
| | | 104 | | /// </summary> |
| | | 105 | | public void Cancel() |
| | 6 | 106 | | { |
| | | 107 | | lock (_lock) |
| | | 108 | | { |
| | 6 | 109 | | if (_disposed) |
| | 0 | 110 | | return; |
| | | 111 | | |
| | 6 | 112 | | _cts?.Cancel(); |
| | 6 | 113 | | } |
| | 6 | 114 | | } |
| | | 115 | | |
| | | 116 | | /// <summary> |
| | | 117 | | /// Executes the provided asynchronous action, handling cancellation and exceptions, and ensuring that the running s |
| | | 118 | | /// </summary> |
| | | 119 | | /// <param name="cancellationToken">The cancellation token to observe.</param> |
| | | 120 | | private async Task ExecuteAsync(CancellationToken cancellationToken) |
| | | 121 | | { |
| | | 122 | | try |
| | | 123 | | { |
| | 27 | 124 | | await _action(cancellationToken).ConfigureAwait(false); |
| | 18 | 125 | | } |
| | 6 | 126 | | catch (OperationCanceledException) |
| | | 127 | | { |
| | 6 | 128 | | if (cancellationToken.IsCancellationRequested) |
| | 6 | 129 | | OnCancelledSafe(); |
| | 6 | 130 | | } |
| | 3 | 131 | | catch (Exception ex) |
| | | 132 | | { |
| | 3 | 133 | | logger?.LogException(ex); |
| | 3 | 134 | | } |
| | | 135 | | finally |
| | 27 | 136 | | { |
| | | 137 | | lock (_lock) |
| | | 138 | | { |
| | 27 | 139 | | _isRunning = false; |
| | 27 | 140 | | _currentTask = null; |
| | 27 | 141 | | } |
| | | 142 | | |
| | 27 | 143 | | NotifyRunningChanged(false); |
| | | 144 | | } |
| | 27 | 145 | | } |
| | | 146 | | |
| | | 147 | | /// <summary> |
| | | 148 | | /// Notifies subscribers that the running state has changed, invoking the onRunningChanged callback if provided, and |
| | | 149 | | /// </summary> |
| | | 150 | | /// <param name="isRunning">A value indicating whether a task is currently running.</param> |
| | | 151 | | private void NotifyRunningChanged(bool isRunning) |
| | | 152 | | { |
| | | 153 | | try |
| | | 154 | | { |
| | 54 | 155 | | onRunningChanged?.Invoke(isRunning); |
| | 54 | 156 | | } |
| | 0 | 157 | | catch (Exception ex) |
| | | 158 | | { |
| | 0 | 159 | | logger?.LogException(ex); |
| | 0 | 160 | | } |
| | 54 | 161 | | } |
| | | 162 | | |
| | | 163 | | /// <summary> |
| | | 164 | | /// Notifies subscribers that the task has been canceled, invoking the onCancelled callback if provided, and logging |
| | | 165 | | /// </summary> |
| | | 166 | | private void OnCancelledSafe() |
| | | 167 | | { |
| | | 168 | | try |
| | | 169 | | { |
| | 6 | 170 | | onCancelled?.Invoke(); |
| | 6 | 171 | | } |
| | 0 | 172 | | catch (Exception ex) |
| | | 173 | | { |
| | 0 | 174 | | logger?.LogException(ex); |
| | 0 | 175 | | } |
| | 6 | 176 | | } |
| | | 177 | | |
| | | 178 | | /// <summary> |
| | | 179 | | /// Disposes the SingleTaskRunner, ensuring that any running task is canceled and that resources are released approp |
| | | 180 | | /// </summary> |
| | | 181 | | public void Dispose() |
| | 30 | 182 | | { |
| | | 183 | | lock (_lock) |
| | | 184 | | { |
| | 30 | 185 | | if (_disposed) |
| | 0 | 186 | | return; |
| | | 187 | | |
| | 30 | 188 | | _disposed = true; |
| | | 189 | | |
| | | 190 | | try |
| | | 191 | | { |
| | 30 | 192 | | _cts?.Cancel(); |
| | 24 | 193 | | } |
| | | 194 | | finally |
| | | 195 | | { |
| | 30 | 196 | | _cts?.Dispose(); |
| | 30 | 197 | | _cts = null; |
| | 30 | 198 | | } |
| | | 199 | | } |
| | 30 | 200 | | } |
| | | 201 | | } |
| | | 202 | | |