Once, when I used the cw snippet in an async method, Visual Studio would use await Console.Out.WriteLineAsync();
instead of the original Console.WriteLine();
. Today I updated Visual Studio to 17.10 and noticed that this feature has been removed.
I would like to ask, is there any difference between these two methods? Or which one is better (besides performance) to use in asynchronous methods?
According to @PanagiotisKanavos’ comments, if a large amount of tasks are used in the code, Console.Out.WriteLineAsync();
is sometimes faster, but in most cases, the performance of both is almost the same.
[Benchmark]
public async ValueTask Benchmark1()
{
await Parallel.ForAsync(0, 50, async (i, ct) =>
{
await Console.Out.WriteLineAsync(LONGTEXT);
await Job();
await Console.Out.WriteLineAsync("short_text");
});
}
[Benchmark]
public async ValueTask Benchmark2()
{
await Parallel.ForAsync(0, 50, async (i, ct) =>
{
Console.WriteLine(LONGTEXT);
await Job();
Console.WriteLine("short_text");
});
}
public async static ValueTask Job()
{
for (int i = 0; i < 12950; i++)
await Task.Yield();
}
2
Answers
If you look into decompiled source of Console.WriteLine you’ll see
So, it’s basically the same.
Console suports writing into main streams In, Out, Err. I think that Console.WriteLine is just a convient wrapper to write into Out, because it’s most commonly used
In terms of performance, the difference is likely negligible because writing text to the console is very fast. Personally, I would say
Console.WriteLine
should be used overConsole.Out.WriteLineAsync
.I’m not sure whether there is a visible difference between
Console.WriteLine
andConsole.Out.WriteLineAsync
.The
Console.Out
property is a staticTextWriter
that opens the console handle and writes text there. EveryWrite
andWriteAsync
method will instead write to the console.When you invoke the
Console.WriteLine
method, it instead invokesConsole.Out.WriteLine
, and since everyWrite
method in theConsole.Out
property writes directly to the console, well, it writes a new line to the console.However,
TextWriter
also has.WriteLineAsync
methods (aside from other asynchronous write methods). Since anything could inherit fromTextWriter
, there needs to be a way to write text asynchronously as well. So,Console.Out.WriteLineAsync
simply writes text with a new line to the console and is implemented because it’s a part ofTextWriter
.Generally, there is probably no difference, since both write to the console.
.WriteLineAsync
is implemented because it has to be implemented, since it’s a method that overrides fromTextWriter
.In synchronous and asynchronous methods, I would personally recommend to use
Console.WriteLine
.See TextWriter Methods.