Asynchronous FileStream & `FileOptions.Asynchronous`
1Concept
`FileStream` interacts with OS file handles. Specifying `FileOptions.Asynchronous` enables true non-blocking I/O completion ports (IOCP on Windows / io_uring on Linux), freeing thread pool threads.
2Architecture Diagram
Thread calls ReadAsync()
│
▼
[ Dispatches Async I/O Request to OS Kernel ] ──> Thread pool thread returns to pool!
│
(Disk Read Finished by Hardware Controller)
│
[ I/O Completion Port (IOCP) wakes worker thread to resume continuation ]3Code Example
C# 13 & .NET 9
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
public class AsyncFileDemo
{
public static async Task Main()
{
string tempPath = Path.GetTempFileName();
byte[] payload = Encoding.UTF8.GetBytes("High-Throughput .NET 9 File Stream Data.");
// True non-blocking Async File I/O
await using (var fs = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
{
await fs.WriteAsync(payload);
}
Console.WriteLine($"File successfully written asynchronously to: {Path.GetFileName(tempPath)}");
File.Delete(tempPath);
}
}4Expected Output
File successfully written asynchronously to: tmp4821.tmp
5Key Takeaways
- ✓Always set `useAsync: true` or `FileOptions.Asynchronous` when performing async file I/O.
- ✓Tune `bufferSize` based on expected read/write chunk sizes (default is 4096 bytes).
- ✓Use `File.ReadAllTextAsync` and `File.WriteAllLinesAsync` for simple utility tasks.