예제 #1
0
        public async Task StopServiceWithWorkUngracefulShutdown()
        {
            var cancellationTokenSource = new CancellationTokenSource();
            int stopCheckDelay          = 300;
            var service = new BackgroundWorkerService();
            await service.StartAsync(cancellationTokenSource.Token);

            bool allowStop             = false;
            bool cancellationWasCalled = false;
            var  workTask = CreateTestTaskAsync(stopCheckDelay, cancellationToken =>
            {
                if (allowStop)
                {
                    cancellationWasCalled = cancellationToken.IsCancellationRequested;
                    return(false);
                }

                return(true);
            });

            service.RunAsync(workTask);
            service.Dispose();
            Assert.IsFalse(service.IsStarted, "Service was still runing despite being disposed");
            Assert.IsTrue(service.IsProcessingTasks, "Service was not processing unfinished work when disposed");
            allowStop = true;
            var waitDelay = stopCheckDelay * 2;
            await Task.Delay(waitDelay); // Make sure our work has a chance to react

            Assert.IsFalse(service.IsProcessingTasks, $"Service was still processing work { waitDelay } milliseconds after stopping");
            Assert.IsTrue(cancellationWasCalled, "Cancellation was not called");
        }
 public void Teardown()
 {
     if (_service != null)
     {
         _service.Dispose();
     }
 }