Other

Streaming large query results with IAsyncEnumerable<T>

DEV Community: #csharp Maayur Dahake
Other

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

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message