Skip to content

Commit

Permalink
ReusableStringWriter: Dispose instance with too big buffer (#1964)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jakimar committed Oct 9, 2023
1 parent 88f76a8 commit 8d0e2ed
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/Serilog/Rendering/ReusableStringWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ class ReusableStringWriter : StringWriter
[ThreadStatic]
static ReusableStringWriter? _pooledWriter;

/// <summary>
/// Max capacity of StringBuilder we keep for next using
/// </summary>
const int StringBuilderCapacityThreshold = 32678;

/// <summary>
/// Gets already created StringWriter if there is one available or creates a new one.
/// </summary>
Expand All @@ -34,9 +39,15 @@ public static StringWriter GetOrCreate(IFormatProvider? formatProvider = null)
/// </summary>
protected override void Dispose(bool disposing)
{
var sb = GetStringBuilder();
if (sb.Capacity > StringBuilderCapacityThreshold)
{
base.Dispose();
return;
}
// We don't call base.Dispose because all it does is mark the writer as closed so it can't be
// written to and we want to keep it open as reusable writer.
GetStringBuilder().Clear();
sb.Clear();
_pooledWriter = this;
}
}

0 comments on commit 8d0e2ed

Please sign in to comment.