Home > database >  Mac OS VS Code: Why does Console.Write("X") method write nothing into console?
Mac OS VS Code: Why does Console.Write("X") method write nothing into console?

Time:10-10

Mac OS (v12.6)
VS Code (v1.72.0)
dotnet v6.0.401

Simple code:

for (int i = 0; i < 1000;   i)
{
    Console.WriteLine("X");
    // Console.Write("X");
}

Result: enter image description here

Good! I see console output.

Ok. Now I try to do the same but with Console.Write method:

for (int i = 0; i < 1000;   i)
{
    //Console.WriteLine("X");
    Console.Write("X");
}

Result: enter image description here

I see nothing now...

Why does Console.Write("X") method write nothing? How can I solve the problem?

P.S. Console.Out.Flush(); doesn't help.
P.S.2. If I add Console.WriteLine(); code line after my loop then I get the expected output (thanks to @jmcilhinney). But why I am to add it?

CodePudding user response:

The answer to this is probably in the dotnet/sdk Git Repository at the link below.

https://github.com/dotnet/sdk/issues/5928#issuecomment-215895840

Comment from the GIT Repo

This is because our StreamForwarder that takes output from the real process and forwards it to the process running dotnet run only writes when it hits a newline:

Code that waits for the flush

  while ((readCharacterCount = reader.Read(buffer, 0, bufferSize)) > 0)
        {
            currentCharacter = buffer[0];

            if (currentCharacter == s_flushBuilderCharacter)
            {
                WriteBuilder();
            }
            else if (! s_ignoreCharacters.Contains(currentCharacter))
            {
                _builder.Append(currentCharacter);
            }
        }

CodePudding user response:

Basically, Console.Write(); appends to whatever hasn't been flushed to the console yet. Console.WriteLine(); is required to flush to the console.

This code:

Console.Write("x");
Console.Write("y");
Console.Write("z");
Console.WriteLine();

Will produce: "xyz" in the Console

https://learn.microsoft.com/en-us/dotnet/api/system.console.write?view=net-6.0

  • Related