
ToListAsync Loads Everything: Buffering vs Streaming Large Results in EF Core
- كاتب موثّق
- EF Core 10
محتويات المقال
await db.Orders.ToListAsync(), passes code review because it's "async all the way down", and runs in seconds against the test database. In production, the container is killed for running out of memory a few minutes after midnight. Someone switches the loop to await foreach over AsAsyncEnumerable(), and the memory graph still climbs until the end of the export.
The common misconception
ToListAsync is async, it's the safe way to process a very large result set without memory pressure. Async is the scalable choice, so the async version must be the one that handles big data.
ToListAsync is the async method every example uses, and await reads as if rows are processed as they arrive. But async solves a thread problem. How many rows sit in memory is a different question, and ToListAsync answers it with "all of them".
What actually happens
Async is about the thread, not the rows
ToListAsync returns a Task<List<T>>, which can only complete once the last row is in the list. That's what EF's guide calls buffering: all results loaded into memory, so memory grows with the row count. In a test with EF Core 10 on SQL Server LocalDB, 200,000 orders with a 100-character note each kept about 115 MB on the managed heap, and the first row was available only after about 1.4 seconds, when the whole result had arrived.
Streaming hands you one row at a time
AsAsyncEnumerable() with await foreach streams. In the same test, a no-tracking stream grew the heap by less than 1 MB, and the first row arrived after about 0.1 seconds.
The change tracker is a second buffer
SaveChanges. The tracked stream in the test ended with 200,000 tracked entries and about 113 MB, almost the same as the list. The tracking docs give two ways out: AsNoTracking(), or a projection that contains no entity types, which isn't tracked at all. Even ToListAsync with AsNoTracking() dropped to about 54 MB, so roughly half of the original cost was the tracker.
EF sometimes buffers for you
EnableRetryOnFailure, the no-tracking stream in the test held about 51 MB and its first row took about a second. Combine that strategy with ToListAsync, and the guide notes the results are loaded twice.
A stream keeps the connection busy
AsAsyncEnumerable reference says multiple active operations on one context aren't supported. In the test, calling SaveChangesAsync inside the loop failed with There is already an open DataReader associated with this Connection which must be closed first.
The fix: stream reads, batch writes
using Microsoft.EntityFrameworkCore;public static class OrderExport{ public static async Task WriteAsync( ShopDb db, TextWriter csv, CancellationToken ct) { // Async, yet every order is loaded and tracked before line one var orders = await db.Orders.ToListAsync(ct); foreach (var o in orders) await csv.WriteLineAsync($"{o.Id},{o.CustomerId},{o.Total}"); }}using Microsoft.EntityFrameworkCore;public static class OrderExport{ public static async Task WriteAsync( ShopDb db, TextWriter csv, CancellationToken ct) { // A projection isn't tracked; AsAsyncEnumerable reads row by row var rows = db.Orders .Select(o => new { o.Id, o.CustomerId, o.Total }) .AsAsyncEnumerable(); await foreach (var o in rows.WithCancellation(ct)) await csv.WriteLineAsync($"{o.Id},{o.CustomerId},{o.Total}"); }}using Microsoft.EntityFrameworkCore;public static class TierRecalculation{ public static async Task RunAsync(ShopDb db, CancellationToken ct) { var lastId = 0; while (true) { // Keyset batch: WHERE Id > lastId, no OFFSET, at most 1,000 rows var batch = await db.Customers.Where(c => c.Id > lastId) .OrderBy(c => c.Id).Take(1_000).ToListAsync(ct); if (batch.Count == 0) break; foreach (var c in batch) c.RecalculateTier(); await db.SaveChangesAsync(ct); db.ChangeTracker.Clear(); // release this batch lastId = batch[^1].Id; } }}ChangeTracker.Clear() and ended at about 113 MB without it. If the change can be written as SQL, ExecuteUpdate avoids loading rows at all.
ToListAsync, tracking | ||||
AsAsyncEnumerable, tracking | ||||
AsAsyncEnumerable, no tracking or projection | ||||
ChangeTracker.Clear() |
How to apply it in your project
Find unbounded lists Look for ToListAsyncandToArrayAsyncon large tables withoutTake, a key filter or paging, especially in jobs and export endpoints.Stream reads without tracking Switch exports and reports to AsAsyncEnumerablewith a projection orAsNoTracking(), and write each row as it arrives.Batch the writes For row-by-row updates, use keyset batches with SaveChangesAsyncandChangeTracker.Clear()per batch, orExecuteUpdatewhen the change fits in SQL.Check what buffers anyway Look for retrying execution strategies and split queries on large reads, and measure memory on production-sized data.
Key takeaways
Async frees the thread during I/O; it doesn't change how many rows end up in memory. ToListAsyncandToArrayAsyncbuffer the whole result before you see the first row.AsAsyncEnumerablestreams, but only stays flat withAsNoTracking()or an entity-free projection.A retrying execution strategy, and split queries without MARS, make EF buffer internally whatever you call. Stream reads, and write in bounded keyset batches that you clear from the change tracker.
📚 المصادر
Efficient Querying: buffering and streaming — EF Core, Microsoft Learn Asynchronous Programming — EF Core, Microsoft Learn EntityFrameworkQueryableExtensions.AsAsyncEnumerable — EF Core API reference, Microsoft Learn Tracking vs. No-Tracking Queries — EF Core, Microsoft Learn Pagination: keyset pagination — EF Core, Microsoft Learn
التعليقات (0)