| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using Microsoft.Extensions.Primitives; |
| | | 3 | | |
| | | 4 | | namespace Elsa.Caching.Services; |
| | | 5 | | |
| | | 6 | | /// <inheritdoc /> |
| | | 7 | | public class ChangeTokenSignalInvoker : IChangeTokenSignalInvoker |
| | | 8 | | { |
| | 1 | 9 | | private readonly ConcurrentDictionary<string, ChangeTokenInfo> _changeTokens = new(); |
| | | 10 | | |
| | | 11 | | /// <inheritdoc /> |
| | | 12 | | public IChangeToken GetToken(string key) |
| | | 13 | | { |
| | 3714 | 14 | | return _changeTokens.GetOrAdd( |
| | 3714 | 15 | | key, |
| | 3714 | 16 | | _ => |
| | 3714 | 17 | | { |
| | 1211 | 18 | | var cancellationTokenSource = new CancellationTokenSource(); |
| | 1211 | 19 | | var changeToken = new CancellationChangeToken(cancellationTokenSource.Token); |
| | 1211 | 20 | | return new ChangeTokenInfo(changeToken, cancellationTokenSource); |
| | 3714 | 21 | | }).ChangeToken; |
| | | 22 | | } |
| | | 23 | | |
| | | 24 | | /// <inheritdoc /> |
| | | 25 | | public ValueTask TriggerTokenAsync(string key, CancellationToken cancellationToken = default) |
| | | 26 | | { |
| | 2673 | 27 | | if (_changeTokens.TryRemove(key, out var changeTokenInfo)) |
| | 1193 | 28 | | changeTokenInfo.TokenSource.Cancel(); |
| | | 29 | | |
| | 2673 | 30 | | return default; |
| | | 31 | | } |
| | | 32 | | |
| | | 33 | | private readonly struct ChangeTokenInfo(IChangeToken changeToken, CancellationTokenSource tokenSource) |
| | | 34 | | { |
| | 4925 | 35 | | public IChangeToken ChangeToken { get; } = changeToken; |
| | 2404 | 36 | | public CancellationTokenSource TokenSource { get; } = tokenSource; |
| | | 37 | | } |
| | | 38 | | } |