AccidentalFish.ApplicationSupport.Core.Policies.Implementation.AsynchronousRegularTimer.ExecuteAsync C# (CSharp) Метод

ExecuteAsync() публичный Метод

public ExecuteAsync ( Action action, CancellationToken cancellationToken, System.Action shutdownAction = null ) : Task
action Action
cancellationToken System.Threading.CancellationToken
shutdownAction System.Action
Результат Task
        public async Task ExecuteAsync(Action<CancellationToken> action, CancellationToken cancellationToken, Action shutdownAction = null)
        {
            if (_delayOnExecute)
            {
                await _taskDelay.Delay(_interval, cancellationToken);
            }
            
            while (!cancellationToken.IsCancellationRequested)
            {
                using (CancellationTokenSource timeLimitedTask = new CancellationTokenSource(_interval))
                {
                    await Task.WhenAll(_threadPoolExecuter.Run(() => action(cancellationToken), timeLimitedTask.Token), _taskDelay.Delay(_interval, cancellationToken));
                }
            }

            shutdownAction?.Invoke();
        }        
    }

Usage Example

        public async Task IntervalAndActionIsTriggered()
        {
            // Arrange
            Mock<IAsynchronousDelay> delay = new Mock<IAsynchronousDelay>();
            Mock<ITimerThreadPoolExecuter> executer = new Mock<ITimerThreadPoolExecuter>();
            executer.Setup(x => x.Run(It.IsAny<Action>(), It.IsAny<CancellationToken>())).Callback((Action a, CancellationToken c) =>
            {
                a();
            }).Returns(Task.FromResult(0));
            AsynchronousRegularTimer timer = new AsynchronousRegularTimer(executer.Object, delay.Object, TimeSpan.FromMilliseconds(PretendDelayInMilliseconds), false);
            CancellationTokenSource source = new CancellationTokenSource();
            int repeatCount = 0;
            
            // Act
            await timer.ExecuteAsync(ct =>
            {
                repeatCount++;
                source.Cancel();                
            }, source.Token);

            // Assert
            Assert.AreEqual(1, repeatCount);
            executer.Verify(x => x.Run(It.IsAny<Action>(), It.IsAny<CancellationToken>()));
            delay.Verify(x => x.Delay(TimeSpan.FromMilliseconds(PretendDelayInMilliseconds), source.Token));
        }
All Usage Examples Of AccidentalFish.ApplicationSupport.Core.Policies.Implementation.AsynchronousRegularTimer::ExecuteAsync