Skip to content

Commit

Permalink
Avoid synchronizing access to TextWriter.Null in Console (#83296)
Browse files Browse the repository at this point in the history
If SetOut/Error are used to silence Console by using TextWriter.Null, we don't need to wrap the writer in a synchronized one like we normally do, since all operations are nops and there's no need to serialize access.
  • Loading branch information
stephentoub authored Mar 11, 2023
1 parent a524575 commit 35f87ec
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions src/libraries/System.Console/src/System/Console.cs
Original file line number Diff line number Diff line change
Expand Up @@ -235,16 +235,16 @@ static TextWriter EnsureInitialized()

private static TextWriter CreateOutputWriter(Stream outputStream)
{
return TextWriter.Synchronized(outputStream == Stream.Null ?
StreamWriter.Null :
new StreamWriter(
return outputStream == Stream.Null ?
TextWriter.Null :
TextWriter.Synchronized(new StreamWriter(
stream: outputStream,
encoding: OutputEncoding.RemovePreamble(), // This ensures no prefix is written to the stream.
bufferSize: WriteBufferSize,
leaveOpen: true)
{
AutoFlush = true
});
{
AutoFlush = true
});
}

private static StrongBox<bool>? _isStdInRedirected;
Expand Down Expand Up @@ -696,7 +696,15 @@ public static void SetOut(TextWriter newOut)
{
ArgumentNullException.ThrowIfNull(newOut);

newOut = TextWriter.Synchronized(newOut);
// Ensure all access to the writer is synchronized. If it's the known Null
// singleton writer, which may be used if someone wants to suppress all
// console output, we needn't add synchronization because all operations
// are nops.
if (newOut != TextWriter.Null)
{
newOut = TextWriter.Synchronized(newOut);
}

lock (s_syncObject)
{
s_isOutTextWriterRedirected = true;
Expand All @@ -708,7 +716,12 @@ public static void SetError(TextWriter newError)
{
ArgumentNullException.ThrowIfNull(newError);

newError = TextWriter.Synchronized(newError);
// Ensure all access to the writer is synchronized. See comment in SetOut.
if (newError != TextWriter.Null)
{
newError = TextWriter.Synchronized(newError);
}

lock (s_syncObject)
{
s_isErrorTextWriterRedirected = true;
Expand Down

0 comments on commit 35f87ec

Please sign in to comment.