Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AsyncWrapper: Improve performance when blocking #3435

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 9 additions & 10 deletions src/NLog/Targets/Wrappers/ConcurrentRequestQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ public ConcurrentRequestQueue(int requestLimit, AsyncTargetWrapperOverflowAction
public override bool Enqueue(AsyncLogEventInfo logEventInfo)
{
long currentCount = Interlocked.Increment(ref _count);
bool queueWasEmpty = currentCount == 1; // Inserted first item in empty queue
if (currentCount > RequestLimit)
{
InternalLogger.Debug("Async queue is full");
Expand All @@ -91,18 +92,19 @@ public override bool Enqueue(AsyncLogEventInfo logEventInfo)
if (_logEventInfoQueue.TryDequeue(out var lostItem))
{
InternalLogger.Debug("Discarding one element from queue");
currentCount = Interlocked.Decrement(ref _count);
queueWasEmpty = Interlocked.Decrement(ref _count) == 1 || queueWasEmpty;
OnLogEventDropped(lostItem.LogEvent);
break;
}
Interlocked.Decrement(ref _count);
currentCount = Interlocked.Increment(ref _count);
currentCount = Interlocked.Read(ref _count);
queueWasEmpty = true;
} while (currentCount > RequestLimit);
}
break;
case AsyncTargetWrapperOverflowAction.Block:
{
currentCount = WaitForBelowRequestLimit();
WaitForBelowRequestLimit();
queueWasEmpty = true;
}
break;
case AsyncTargetWrapperOverflowAction.Grow:
Expand All @@ -115,10 +117,10 @@ public override bool Enqueue(AsyncLogEventInfo logEventInfo)
}
}
_logEventInfoQueue.Enqueue(logEventInfo);
return currentCount == 1; // Inserted first item in empty queue
return queueWasEmpty;
}

private long WaitForBelowRequestLimit()
private void WaitForBelowRequestLimit()
{
long currentCount;
bool lockTaken = false;
Expand Down Expand Up @@ -146,8 +148,6 @@ private long WaitForBelowRequestLimit()
if (lockTaken)
Monitor.Exit(_logEventInfoQueue);
}

return currentCount;
}

private long TrySpinWaitForLowerCount()
Expand All @@ -157,7 +157,6 @@ private long TrySpinWaitForLowerCount()
SpinWait spinWait = new SpinWait();
for (int i = 0; i <= 20; ++i)
{
Interlocked.Decrement(ref _count);
if (spinWait.NextSpinWillYield)
{
if (firstYield)
Expand All @@ -166,7 +165,7 @@ private long TrySpinWaitForLowerCount()
}

spinWait.SpinOnce();
currentCount = Interlocked.Increment(ref _count);
currentCount = Interlocked.Read(ref _count);
if (currentCount <= RequestLimit)
break;
}
Expand Down