Asynchronous I/O
I have said it before, but this is so important that I have to repeat it here: IO is slow. Every piece of code that works with IO should be done asynchronously. Luckily, most of the classes in the System.IO
namespace have asynchronous members that we can use with async/await.
I would be happy if Microsoft decided to mark all non-asynchronous methods in System.IO
as obsolete.
The naïve approach
Most of the methods you know in System.IO
have an asynchronous version. So, just add the async
postfix to the method name and await it. Simple!
On second thought, no. It is not that simple.
Let me show you an example:
public async Task CreateBigFileNaively(string fileName) { var stream = File.CreateText(fileName); for (int i = 0; i < Int32.MaxValue; i++) { var value = $"This is line {i}"; ...