| | | 1 | | namespace TeleFlow.Telegram; |
| | | 2 | | |
| | | 3 | | public sealed class ChatActionLease : IAsyncDisposable |
| | | 4 | | { |
| | 9 | 5 | | private readonly CancellationTokenSource _disposeCancellation = new(); |
| | | 6 | | private readonly CancellationTokenSource _linkedCancellation; |
| | | 7 | | private readonly CancellationToken _linkedToken; |
| | | 8 | | private readonly Task _repeatTask; |
| | | 9 | | private int _disposed; |
| | | 10 | | |
| | | 11 | | internal ChatActionLease( |
| | | 12 | | ITelegramClient bot, |
| | | 13 | | TelegramChatActionTarget target, |
| | | 14 | | ChatAction action, |
| | | 15 | | TimeProvider timeProvider, |
| | | 16 | | TimeSpan repeatDelay, |
| | | 17 | | CancellationToken cancellationToken) |
| | | 18 | | { |
| | 9 | 19 | | _linkedCancellation = CancellationTokenSource.CreateLinkedTokenSource( |
| | 9 | 20 | | cancellationToken, |
| | 9 | 21 | | _disposeCancellation.Token); |
| | 9 | 22 | | _linkedToken = _linkedCancellation.Token; |
| | 9 | 23 | | _repeatTask = RepeatAsync(bot, target, action, timeProvider, repeatDelay, _linkedToken); |
| | 9 | 24 | | } |
| | | 25 | | |
| | | 26 | | public async ValueTask DisposeAsync() |
| | | 27 | | { |
| | 10 | 28 | | var shouldDispose = Interlocked.Exchange(ref _disposed, 1) == 0; |
| | 10 | 29 | | if (shouldDispose) |
| | | 30 | | { |
| | 9 | 31 | | await _disposeCancellation.CancelAsync().ConfigureAwait(false); |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | try |
| | | 35 | | { |
| | 10 | 36 | | await _repeatTask.ConfigureAwait(false); |
| | 0 | 37 | | } |
| | 9 | 38 | | catch (OperationCanceledException) when (_linkedToken.IsCancellationRequested) |
| | | 39 | | { |
| | 9 | 40 | | } |
| | | 41 | | finally |
| | | 42 | | { |
| | 10 | 43 | | if (shouldDispose) |
| | | 44 | | { |
| | 9 | 45 | | _linkedCancellation.Dispose(); |
| | 9 | 46 | | _disposeCancellation.Dispose(); |
| | | 47 | | } |
| | | 48 | | } |
| | 9 | 49 | | } |
| | | 50 | | |
| | | 51 | | private static async Task RepeatAsync( |
| | | 52 | | ITelegramClient bot, |
| | | 53 | | TelegramChatActionTarget target, |
| | | 54 | | ChatAction action, |
| | | 55 | | TimeProvider timeProvider, |
| | | 56 | | TimeSpan repeatDelay, |
| | | 57 | | CancellationToken cancellationToken) |
| | | 58 | | { |
| | 1 | 59 | | while (true) |
| | | 60 | | { |
| | 10 | 61 | | await Task.Delay(repeatDelay, timeProvider, cancellationToken).ConfigureAwait(false); |
| | 2 | 62 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 2 | 63 | | await ChatActions.SendChatActionAsync(bot, target, action, cancellationToken).ConfigureAwait(false); |
| | | 64 | | } |
| | | 65 | | } |
| | | 66 | | } |