Skip to content

Console.WriteLine() is not thread-safe #53751

Closed as not planned
Closed as not planned

Description

@Fleischhauer

Description

Apart from beeing a convoluted mess and using way too much coloring using escape-sequences (using silkfire/Pastel), and that in this case I put out much more messages than normally for a debug session, my logger still uses only one Console.WriteLine() to output a message.

And still, the linebreak get's swallowed sometimes randomly on concurrent access.
How can that be? I thought it's thread-safe.

Configuration

  • Which version of .NET is the code running on? 5.0.300
  • What OS and version, and what distro if applicable? Windows 10 2004
  • What is the architecture (x64, x86, ARM, ARM64)? x64

Regression?

I use this logger since Core 3.0 and never noticed this, but I also never really fired so many messages concurrently maybe.

210605_0211_VsDebugConsole
210605_0212_VsDebugConsole

Activity

  1. ghost added
    untriaged
    on Jun 5, 2021
  2. MarkPflug commented on Jun 5, 2021

    @MarkPflug
    Contributor

    Not to comment on the thread safety issue, but as a workaround have you tried using Console.Write and append the linefeed yourself? It sounds like you're already assembling a string so maybe you have an opportunity to append the newline before the string is constructed.

  3. Fleischhauer commented on Jun 5, 2021

    @Fleischhauer
    Author

    Not to comment on the thread safety issue, but as a workaround have you tried using Console.Write and append the linefeed yourself? It sounds like you're already assembling a string so maybe you have an opportunity to append the newline before the string is constructed.

    That is so simple, it didn't even come to my mind lol.
    Is there even a difference beetween Console.Write() with a linebreak in the string and Console.WriteLine without?

  4. stephentoub commented on Jun 5, 2021

    @stephentoub
    Member

    Can you share a repro?

  5. huoyaoyuan commented on Jun 5, 2021

    @huoyaoyuan
    Member

    Curious how this can happen. Looking at console implementation, Console uses TextWriter.Synchronized which has [MethodImpl(MethodImplOptions.Synchronized)] on every method.

    If there is synchronization issue for new line, you should observe duplicate new line as well as missed new line. Your repro indicates that some new lines are eaten.

  6. Fleischhauer commented on Jun 5, 2021

    @Fleischhauer
    Author

    Replacing WriteLine(logString) with Write(logString & vbCrLf) fixed it for me, soo~
    I don't bother to show my spagetthi code, but the project is private and I don't have time to extract it to something working right now, sorry.

    But I can show you the parts which cause it if that helps.
    (Edit: Github seems to hate VB.Net too lol - https://pastebin.com/LbnFprk4)
    The string was build like this:

            Dim logString = ""
            ' LogLvl 
            logString &= $"{levelS,8}".Pastel(msgColor)
    
            '         [00:00:00:000]
            logString &= " [".Pastel(Color.FromKnownColor(KnownColor.Gray))
            logString &= $"{dNow.Hour:00}".Pastel(timeColor1)
            logString &= $":".Pastel(Color.FromKnownColor(KnownColor.DarkGray))
            logString &= $"{dNow.Minute:00}".Pastel(timeColor1)
            logString &= $":".Pastel(Color.FromKnownColor(KnownColor.DarkGray))
            logString &= $"{dNow.Second:00}".Pastel(timeColor1)
            logString &= $".".Pastel(Color.FromKnownColor(KnownColor.DimGray))
            logString &= $"{dNow.Millisecond:000}".Pastel(timeColor2)
            logString &= "] ".Pastel(Color.FromKnownColor(KnownColor.Gray))
    
            '                        Source(0)
            logString &= source.Pastel(srcColor)
            logString &= "(".Pastel(Color.FromKnownColor(KnownColor.Gray))
            If line > 0 Then
                logString &= $"{line,3}".Pastel(Color.FromKnownColor(KnownColor.DarkGray))
            End If
            logString &= ")".Pastel(Color.FromKnownColor(KnownColor.Gray))
            '                                     Log Message...
            logString &= " " & message.Pastel(msgColor)
    
            ' Exception in new line
            If ex IsNot Nothing Then
                logString &= vbCrLf & LogPadding & ex.ToString().Pastel(Color.FromKnownColor(KnownColor.Crimson))
            End If
    
            Console.WriteLine(logString)

    And in this case called only from one method. In the case of the screenshot from this For Each:

    For Each remoteFile In remoteFiles
        Log(LogLvl.Debug3, $"{If(remoteFile.IsDirectory, "Dir", "File"),4} [{remoteFile.IsRegularFile}] {remoteFile.LastWriteTime} {remoteFile.FullName.Substring(remoteRelFilePathPos)}")
    
        'Ignore directorys
        If remoteFile.IsDirectory Then
            Log(LogLvl.Debug, remoteFile.Name & " is directory")
            Continue For
        End If
    
        'Ignore system files
        If Not remoteFile.IsRegularFile Then
            Log(LogLvl.Quit, "RemoteFile is no regular file: " & remoteFile.Name)
            Continue For
        End If
    
        'Get relative path
        Dim remoteRelFilePath = remoteFile.FullName.Substring(remoteRelFilePathPos)
    
        'Save to dict
        remoteFilesChecked.Add(remoteRelFilePath, remoteFile)
    
        'Add if file is not in local files
        If Not localFilesChecked.ContainsKey(remoteRelFilePath) Then
            Log(LogLvl.Warning, "Local does not contain " & remoteFile.Name)
            toDownload.Add(remoteFile)
            Continue For
        End If
    
        'Add if file is at least a second newer (to prevent precision errors with different file-systems)
        Dim localLastWrite = localFilesChecked(remoteRelFilePath).LastWriteTimeUtc.AddSeconds(1)
        If localLastWrite.CompareTo(remoteFile.LastWriteTimeUtc) < 0 Then
            Log(LogLvl.Info, $"{remoteFile.Name} is newer than local file (local < remote)" & vbCrLf & $"({localFilesChecked(remoteRelFilePath).LastWriteTimeUtc} < {remoteFile.LastWriteTimeUtc}) UTC" & vbCrLf & $"({localFilesChecked(remoteRelFilePath).LastWriteTime} < {remoteFile.LastWriteTime}) LOCAL")
            toDownload.Add(remoteFile)
            Continue For
        End If
    
        Log(LogLvl.Success, remoteFile.Name & " is already up to date locally")
    Next
  7. added this to the Future milestone on Jul 13, 2021
  8. removed
    untriaged
    on Jul 13, 2021
  9. remcoros commented on Jan 19, 2022

    @remcoros
    Member

    I just ran into this too.

    A console tool (net6.0) that runs multiple operations in parallel using Task.Run(..) and write progress using Console.WriteLine.

    The result (when it happens) is the same as op, something like:

    result from process1\r\n
    result from process2\r\n
    result from process3result from process4\r\n
    \r\n
    result from process5\r\n

    Using Console.Write(message + Environment.NewLine) also fixed it for me.

  10. stephentoub commented on Jan 19, 2022

    @stephentoub
    Member

    @remcoros, can you share a repro? The whole of WriteLine is inside of a lock (a MethodImplOptions.Synchronized method), so it's not clear how this could happen.

  11. remcoros commented on Jan 19, 2022

    @remcoros
    Member

    Actually, while trying to repro this. I think the bug is in System.Commandline. They provide an IConsole and wrap some input/output text readers and it looks like they are not thread safe.

            public static void WriteLine(this IStandardStreamWriter writer, string value)
            {
                if (writer is null)
                {
                    throw new ArgumentNullException(nameof(writer));
                }
    
                writer.Write(value);
                writer.Write(Environment.NewLine);
            }

    Looking at .NET source I can't see how this could happen also. I think the issue of op might be the same as mine (bug in some console wrapper or the log library itself)

    I'll make an issue on the System.Commandline repo.

  12. stephentoub commented on Jan 19, 2022

    @stephentoub
    Member

    I think the bug is in System.Commandline. They provide an IConsole and wrap some input/output text readers and it looks like they are not thread safe.

    That makes a lot more sense. Thanks!

  13. terrajobst commented on Apr 21, 2022

    @terrajobst
    Contributor

    This could be closed then, right?

  14. adamsitnik commented on Nov 13, 2023

    @adamsitnik
    Member

    This could be closed then, right?

    Right. Thank you all!

  15. locked and limited conversation to collaborators on Dec 14, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions