0

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?

bjorn93
  • 213
  • 1
  • 5
  • ipersonally, i find the description of `useAsync` quite enlightening. the TLDR would be: using async _can_ increase performance, if the application around it is programmed right, or it can decrease it if the application isn't. – Franz Gleichmann Jun 10 '21 at 11:23
  • 3
    You may find [this](https://stackoverflow.com/questions/63217657/why-file-readalllinesasync-blocks-the-ui-thread) interesting. Currently the asynchronous filesystem APIs are not implemented efficiently in .NET. If you set the `useAsync` to `true`, the operation will be considerably slower, while being still mostly synchronous. – Theodor Zoulias Jun 10 '21 at 11:41

0 Answers0