Does Console.WriteLine
block until the output has been written or does it return immediately?
If it does block is there a method of writing asynchronous output to the Console?
WriteLine(String, Object, Object) Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.
WriteLine has an impact on the performance of your specific application is profiling it. Otherwise it's premature optimization. Show activity on this post. If it's for debugging purpose, you should rather use: Debug.
Answers. Yes, they are. Although TextWriter methods are not, Console. Out uses a SyncTextWriter which is thread-safe.
However, Console. WriteLine is very slow, considerably slower than writing to a file.
Does Console.WriteLine block until the output has been written or does it return immediately?
Yes.
If it does block is there a method of writing asynchronous output to the Console?
The solution to writing to the console without blocking is surprisingly trivial if you are using .NET 4.0. The idea is to queue up the text values and let a single dedicated thread do the Console.WriteLine
calls. The producer-consumer pattern is ideal here because it preserves the temporal ordering that is implicit when using the native Console
class. The reason why .NET 4.0 makes this easy is because it has the BlockingCollection class which facilitates the production of a producer-consumer pattern. If you are not using .NET 4.0 then you can get a backport by downloading the Reactive Extensions framework.
public static class NonBlockingConsole { private static BlockingCollection<string> m_Queue = new BlockingCollection<string>(); static NonBlockingConsole() { var thread = new Thread( () => { while (true) Console.WriteLine(m_Queue.Take()); }); thread.IsBackground = true; thread.Start(); } public static void WriteLine(string value) { m_Queue.Add(value); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With