Skip to content

Commit 658a8e4

Browse files
authored
Fix the NREs when writing to console from multiple threads (#25440)
The WriteImpl() method should always be called within a lock on _instanceLock to ensure thread safety.
1 parent 05ca88b commit 658a8e4

1 file changed

Lines changed: 14 additions & 3 deletions

File tree

src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -709,9 +709,14 @@ private void WriteLineToConsole()
709709
/// </exception>
710710
public override void Write(string value)
711711
{
712-
WriteImpl(value, newLine: false);
712+
lock (_instanceLock)
713+
{
714+
WriteImpl(value, newLine: false);
715+
}
713716
}
714717

718+
// The WriteImpl() method should always be called within a lock on _instanceLock
719+
// to ensure thread safety and prevent issues in multi-threaded scenarios.
715720
private void WriteImpl(string value, bool newLine)
716721
{
717722
if (string.IsNullOrEmpty(value) && !newLine)
@@ -845,7 +850,10 @@ private void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, s
845850
/// </exception>
846851
public override void WriteLine(string value)
847852
{
848-
this.WriteImpl(value, newLine: true);
853+
lock (_instanceLock)
854+
{
855+
this.WriteImpl(value, newLine: true);
856+
}
849857
}
850858

851859
/// <summary>
@@ -862,7 +870,10 @@ public override void WriteLine(string value)
862870
/// </exception>
863871
public override void WriteLine()
864872
{
865-
this.WriteImpl(Environment.NewLine, newLine: false);
873+
lock (_instanceLock)
874+
{
875+
this.WriteImpl(Environment.NewLine, newLine: false);
876+
}
866877
}
867878

868879
#region Word Wrapping

0 commit comments

Comments
 (0)