Skip to content

Commit

Permalink
BufferingTargetWrapper - Avoid Timer starvation when SlidingTimeout =…
Browse files Browse the repository at this point in the history
… true
  • Loading branch information
snakefoot authored and 304NotModified committed May 28, 2019
1 parent 458feb4 commit 267d29e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
7 changes: 6 additions & 1 deletion src/NLog/Common/LogEventInfoBuffer.cs
Expand Up @@ -65,10 +65,15 @@ public LogEventInfoBuffer(int size, bool growAsNeeded, int growLimit)
}

/// <summary>
/// Gets the number of items in the array.
/// Gets the capacity of the buffer
/// </summary>
public int Size => _buffer.Length;

/// <summary>
/// Gets the number of items in the buffer
/// </summary>
internal int Count { get { lock (_lockObject) return _count; } }

/// <summary>
/// Adds the specified log event to the buffer.
/// </summary>
Expand Down
23 changes: 18 additions & 5 deletions src/NLog/Targets/Wrappers/BufferingTargetWrapper.cs
Expand Up @@ -187,10 +187,7 @@ protected override void CloseTarget()
_flushTimer = null;
if (currentTimer.WaitForDispose(TimeSpan.FromSeconds(1)))
{
lock (_lockObject)
{
WriteEventsInBuffer("Closing Target");
}
WriteEventsInBuffer("Closing Target");
}
}

Expand Down Expand Up @@ -228,15 +225,24 @@ protected override void Write(AsyncLogEventInfo logEvent)

private void FlushCallback(object state)
{
bool lockTaken = false;

try
{
lock (_lockObject)
int timeoutMilliseconds = Math.Min(FlushTimeout / 2, 100);
lockTaken = Monitor.TryEnter(_lockObject, timeoutMilliseconds);
if (lockTaken)
{
if (_flushTimer == null)
return;

WriteEventsInBuffer(null);
}
else
{
if (_buffer.Count > 0)
_flushTimer?.Change(FlushTimeout, -1); // Schedule new retry timer
}
}
catch (Exception exception)
{
Expand All @@ -247,6 +253,13 @@ private void FlushCallback(object state)
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
}
finally
{
if (lockTaken)
{
Monitor.Exit(_lockObject);
}
}
}

private void WriteEventsInBuffer(string reason)
Expand Down

0 comments on commit 267d29e

Please sign in to comment.