diff --git a/EonaCat.Logger/EonaCat.Logger.csproj b/EonaCat.Logger/EonaCat.Logger.csproj index 1bb4559..5b92fbe 100644 --- a/EonaCat.Logger/EonaCat.Logger.csproj +++ b/EonaCat.Logger/EonaCat.Logger.csproj @@ -13,8 +13,8 @@ EonaCat (Jeroen Saey) EonaCat;Logger;EonaCatLogger;Log;Writer;Jeroen;Saey - 1.5.6 - 1.5.6 + 1.5.7 + 1.5.7 README.md True LICENSE diff --git a/EonaCat.Logger/EonaCatCoreLogger/Internal/BatchingLoggerProvider.cs b/EonaCat.Logger/EonaCatCoreLogger/Internal/BatchingLoggerProvider.cs index ac46b63..79fd59d 100644 --- a/EonaCat.Logger/EonaCatCoreLogger/Internal/BatchingLoggerProvider.cs +++ b/EonaCat.Logger/EonaCatCoreLogger/Internal/BatchingLoggerProvider.cs @@ -68,20 +68,23 @@ public abstract class BatchingLoggerProvider : ILoggerProvider, IDisposable } set => _loggerSettings = value; - } + } + + private SemaphoreSlim _writeSemaphore = new SemaphoreSlim(1, 1); public bool IsStarted { get; set; } public bool UseMask { get; set; } - public void Dispose() + public async void Dispose() { while (!_messageQueue.IsEmpty) { - Task.Delay(10); + // Do nothing, just wait for the queue to be empty + await Task.Delay(1000); } _isDisposing = true; - StopAsync().GetAwaiter().GetResult(); + await StopAsync().ConfigureAwait(false); GC.SuppressFinalize(this); } @@ -92,40 +95,43 @@ public abstract class BatchingLoggerProvider : ILoggerProvider, IDisposable } protected abstract Task WriteMessagesAsync(IEnumerable messages, CancellationToken token); - private async Task ProcessLogQueueAsync(object state) - { - while (!_cancellationTokenSource.IsCancellationRequested) - { - var limit = _batchSize <= 0 ? int.MaxValue : _batchSize; - while (limit > 0 && _messageQueue.TryDequeue(out var message)) - { - _currentBatch.Add(message); - limit--; - } + private async Task ProcessLogQueueAsync(object state) + { + while (!_cancellationTokenSource.IsCancellationRequested) + { + var limit = _batchSize <= 0 ? int.MaxValue : _batchSize; + while (limit > 0 && _messageQueue.TryDequeue(out var message)) + { + _currentBatch.Add(message); + limit--; + } + + if (_currentBatch.Count > 0) + { + try + { + if (_isDisposing) + { + return; + } + + await _writeSemaphore.WaitAsync(); + await WriteMessagesAsync(_currentBatch, _cancellationTokenSource.Token).ConfigureAwait(false); + _currentBatch.Clear(); + } + catch + { + // ignored + } + finally + { + _writeSemaphore.Release(); + } + } + await Task.Delay(500); + } + } - if (_currentBatch.Count > 0) - { - try - { - if (_isDisposing) - { - return; - } - - lock (_writeLock) - { - WriteMessagesAsync(_currentBatch, _cancellationTokenSource.Token).ConfigureAwait(false); - _currentBatch.Clear(); - } - } - catch - { - // ignored - } - } - Thread.Sleep(10); - } - } protected async Task WriteStartMessage() {