Calling Console.WriteLine from multiple threads

.Netconsole.writeline

.Net Problem Overview


Why does Console.WriteLine work from multiple threads?

.Net Solutions


Solution 1 - .Net

The console class handles the thread synchronization for you.

From the documentation of Console:

> I/O operations using these streams are > synchronized, which means multiple > threads can read from, or write to, > the streams.

Solution 2 - .Net

There is a bug in .NET 4.5 CLR which makes Console.WriteLine not work from multiple threads if you use Console.ReadKey. It is fixed in some Windows versions, but in 8.1 Windows Update does not find it yet.

https://stackoverflow.com/questions/6498756/infrequent-hangs-in-a-multi-threaded-c-sharp-console-application-when-using-cons

https://stackoverflow.com/questions/18357256/using-console-writeline-in-a-timer-why-it-would-appear-to-exit

Solution 3 - .Net

Multiple threads write to the same output when using Console.WriteLine, generally your screen by default.

Solution 4 - .Net

The console and your code are 2 seperate applications

The console window is not your application. A console application is invisable, your application does not contain the console. The console is installed into windows itself.

Console.Writeline() is a Message

It writes to a TextStream. Microsoft's console process simply waits for new streamtext to display.

The 'Console Application' name does not make it a console

The difference with ui projects is that a console application comes with a simplified set of references, and relies on input / output stream to communicate with the user.

You dont even need the console, you could build your own console, or use a debugger to view and write to it.

Comparison with notepad

If a file was a message, and notepad opened the filestream saved by your code. It wouldnt have mattered from which thread you saved the file. You are not accesing any ui.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser113476View Question on Stackoverflow
Solution 1 - .NetReed CopseyView Answer on Stackoverflow
Solution 2 - .NetJure ŠpikView Answer on Stackoverflow
Solution 3 - .NetChris BallanceView Answer on Stackoverflow
Solution 4 - .Netfazioli fairmontView Answer on Stackoverflow