| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | |
| | | 3 | | namespace Elsa.Testing.Shared.Services; |
| | | 4 | | |
| | | 5 | | public class SignalManager |
| | | 6 | | { |
| | 1 | 7 | | private readonly ConcurrentDictionary<object, TaskCompletionSource<object?>> _signals = new(); |
| | | 8 | | |
| | | 9 | | public async Task<T> WaitAsync<T>(object signal, int millisecondsTimeout = 60000) |
| | | 10 | | { |
| | 26 | 11 | | var result = await WaitAsync(signal, millisecondsTimeout); |
| | | 12 | | |
| | 26 | 13 | | if(result is not T typedResult) |
| | 0 | 14 | | throw new InvalidCastException($"Signal '{signal}' was not of type '{typeof(T).Name}'."); |
| | | 15 | | |
| | 26 | 16 | | return typedResult; |
| | 26 | 17 | | } |
| | | 18 | | |
| | | 19 | | public async Task<object?> WaitAsync(object signal, int millisecondsTimeout = 60000) |
| | | 20 | | { |
| | 26 | 21 | | var taskCompletionSource = GetOrCreate(signal); |
| | 26 | 22 | | using var cancellationTokenSource = new CancellationTokenSource(millisecondsTimeout); |
| | | 23 | | try |
| | | 24 | | { |
| | 26 | 25 | | await Task.WhenAny(taskCompletionSource.Task, Task.Delay(millisecondsTimeout, cancellationTokenSource.Token) |
| | 26 | 26 | | cancellationTokenSource.Token.ThrowIfCancellationRequested(); |
| | 26 | 27 | | _signals.TryRemove(signal, out _); |
| | 26 | 28 | | return await taskCompletionSource.Task; |
| | | 29 | | } |
| | 0 | 30 | | catch (OperationCanceledException) |
| | | 31 | | { |
| | 0 | 32 | | throw new TimeoutException($"Signal '{signal}' timed out after {millisecondsTimeout} milliseconds."); |
| | | 33 | | } |
| | 26 | 34 | | } |
| | | 35 | | |
| | | 36 | | public void Trigger(object signal, object? result = null) |
| | | 37 | | { |
| | 5539 | 38 | | var taskCompletionSource = GetOrCreate(signal); |
| | | 39 | | |
| | 5539 | 40 | | if (taskCompletionSource.Task.IsCompleted) |
| | 5252 | 41 | | return; |
| | | 42 | | |
| | 287 | 43 | | taskCompletionSource.SetResult(result); |
| | 287 | 44 | | } |
| | | 45 | | |
| | | 46 | | private TaskCompletionSource<object?> GetOrCreate(object eventName) |
| | | 47 | | { |
| | 5852 | 48 | | return _signals.GetOrAdd(eventName, _ => new TaskCompletionSource<object?>(TaskCreationOptions.RunContinuationsA |
| | | 49 | | } |
| | | 50 | | } |