public void dispose_executes_only_on_the_first_call() { var mockLogger = new TestLogger(LogLevel.Trace); var sideEffect = false; void DisposeAction() { sideEffect = true; // ReSharper disable once AccessToModifiedClosure mockLogger.Debug()?.Log($"Inside {nameof(DisposeAction)}"); } var disposableHelper = new DisposableHelper(); const string disposableDesc = "test_disposable"; var isDisposedByThisCall = disposableHelper.DoOnce(mockLogger, disposableDesc, DisposeAction); isDisposedByThisCall.Should().BeTrue(); sideEffect.Should().BeTrue(); disposableHelper.HasStarted.Should().BeTrue(); mockLogger.Lines.Should().HaveCount(3); mockLogger.Lines.First().Should().MatchEquivalentOf($"*Starting to dispose {disposableDesc}*"); mockLogger.Lines.Skip(1).First().Should().MatchEquivalentOf($"*Inside {nameof(DisposeAction)}*"); mockLogger.Lines.Skip(2).First().Should().MatchEquivalentOf($"*Finished disposing {disposableDesc}*"); mockLogger = new TestLogger(LogLevel.Trace); sideEffect = false; isDisposedByThisCall = disposableHelper.DoOnce(mockLogger, disposableDesc, DisposeAction); isDisposedByThisCall.Should().BeFalse(); sideEffect.Should().BeFalse(); disposableHelper.HasStarted.Should().BeTrue(); mockLogger.Lines.Should().ContainSingle(); mockLogger.Lines.First().Should().MatchEquivalentOf($"*{disposableDesc}*already disposed*"); }
public void Dispose() { if (!_isEnabled) { _logger.Debug()?.Log("Disabled - nothing to dispose, exiting"); return; } _disposableHelper.DoOnce(_logger, _dbgName, () => { _logger.Debug()?.Log("Calling CancellationTokenSource.Cancel()..."); // ReSharper disable once AccessToDisposedClosure CancellationTokenSource.Cancel(); _logger.Debug()?.Log("Called CancellationTokenSource.Cancel()"); _logger.Debug() ?.Log("Waiting for loop to exit... Is cancellation token signaled: {IsCancellationRequested}", CancellationTokenSource.Token.IsCancellationRequested); _loopCompleted.Wait(); _logger.Debug()?.Log("Disposing _singleThreadTaskScheduler ..."); _singleThreadTaskScheduler.Dispose(); _logger.Debug()?.Log("Disposing HttpClient..."); HttpClient.Dispose(); _logger.Debug()?.Log("Disposing CancellationTokenSource..."); CancellationTokenSource.Dispose(); _logger.Debug()?.Log("Exiting..."); }); }
public void Dispose() => _disposableHelper.DoOnce(_logger, ThisClassName, () => { _logger.Debug()?.Log("Signalling _cancellationTokenSource"); _cancellationTokenSource.Cancel(); _logger.Debug()?.Log("Waiting for _singleThreadTaskScheduler thread `{ThreadName}' to exit", _singleThreadTaskScheduler.Thread.Name); _singleThreadTaskScheduler.Thread.Join(); _logger.Debug()?.Log("_singleThreadTaskScheduler thread exited - disposing of _cancellationTokenSource and exiting"); _cancellationTokenSource.Dispose(); });