This is what is typically done if you want to use, say, StreamWriter
to write to a file asynchronously:
public static async Task Main()
{
string fileName = "output.txt";
string message = "Something";
using var writer = new StreamWriter(fileName);
await writer.WriteLineAsync(message);
}
However, I noticed that the FileStream
class has a constructor which allows you to indicate the stream itself is asynchronous. By default, useAsync
is false
if you use a different constructor, i.e., the stream is synchronous by default (?) . Does this mean that in the code above, it's better to open an asynchronous stream and then pass it to StreamWriter
like this:
public static async Task Main()
{
string fileName = "output.txt";
string message = "Something";
using var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true);
using var writer = new StreamWriter(fs);
await writer.WriteLineAsync(message);
}
Does this way make any difference here (or in general), and is it better asynchronous code?