A reporting endpoint that pulled more than 50,000 rows into memory with `ToListAsync()` was causing erratic Gen2 GC pauses. The post shows how returning `IAsyncEnumerable<T>` from EF Core streams rows straight to the HTTP response and keeps memory flat.
Key points
- `ToListAsync()` buffers the whole result set, multiplying allocations again during JSON serialization.
- `AsAsyncEnumerable()` skips the intermediate `List<T>` backing array entirely.
- ASP.NET Core writes the returned `IAsyncEnumerable<Order>` straight into the response pipeline.
- Memory stays flat regardless of row count and Time-to-First-Byte drops sharply.
- A mid-stream failure can hit a disposed `DbContext`, so middleware must handle it gracefully.
Real-world use
- Reporting endpoints that return tens of thousands of historical transaction rows
- Large data exports that must keep memory usage flat
- ASP.NET Core APIs that need to free worker threads under peak traffic
This summary was generated by the agent from the original post on DEV Community: #csharp. The full text and all rights belong to its author and publisher. Go to original