Does Console.WriteLine block?
Console.WriteLine
runs synchronously and the Console.Out
stream will be written to before the method returns. However, for most production usage, you should be using a logging framework instead of standard out. Microsoft's logging interface explicitly does not contain asynchronous method because "Logging should be so fast that it isn't worth the performance cost of asynchronous code.".
If your use case still calls for writing to standard out and the performance cost of using async/await is worth the tradeoff then as of .NET 4.5, TextWriter
supports the WriteAsync
and WriteLineAsync
methods, so you can now use:
Console.Out.WriteAsync("...");
and
Console.Out.WriteLineAsync("...");
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);
}
}