Once, when I used the cw snippet (type cwTAB) 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 the snippet produces Console.WriteLine();
in async methods.
Due to this behavior in the past, I have been using await Console.Out.WriteLineAsync();
in asynchronous methods, so initially I thought it might be a bug. But after actual testing, I did not find any problems with using Console.WriteLine();
in asynchronous methods.
I would like to ask, is there any difference between these two methods? If there is no difference, why did Visual Studio recommend await Console.Out.WriteLineAsync();
in old versions?
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();
}
async void
delegates, which can't be awaited. That meansBenchmark1
can easily finish before the lines are written. Second, only one thing can be written to the console otherwise the output would be jumbled. This restriction is enforced by .NET and I suspect, the OS itself. It doesn't if the console is accessed through a TextWriter or as a StreamTextWriter.WriteLineAsync
doesn't write to the output faster. Like all async IO, it avoids blocking the caller thread while an IO operation is going on. In a desktop app that means the UI thread can draw the UI instead of freezing. In a web app it means the thread can process other requests. The necessary synchronization through callbacks/IO completion ports means async operations are slightly slower than sync.