الانتقال إلى المحتوى
.NETEF Core· 7 دقائق للقراءة

ToListAsync Loads Everything: Buffering vs Streaming Large Results in EF Core

Async frees the thread, not the memory. For large results, stream with AsAsyncEnumerable and no tracking, write in bounded batches, and know when EF buffers for you.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • EF Core 10
محتويات المقال

A nightly job exports every order to a CSV file. It starts with 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

The belief: because 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.

Half of that is good advice. EF Core's performance guide tells you to always prefer asynchronous APIs, because synchronous ones block a thread for the whole database round trip. 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

EF Core's async docs say async operations avoid blocking a thread while the query runs, and have the same effects as their sync counterparts. 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

means EF gives you one result at a time and never holds the whole set. The guide puts it this way: in principle, a streaming query needs the same memory for one row or a thousand. 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

Streaming the rows isn't enough if EF keeps every entity anyway. A tracking query registers each entity and stores a snapshot of its values for 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

The guide lists two cases where EF buffers internally, however you consume the query: a retrying execution strategy, so a retry can return the same results, and split queries, where all but the last query's results are buffered unless MARS is enabled on SQL Server. With 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

While you enumerate, the query's data reader stays open. The 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

C# OrderExport.cs
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}");    }}

The projection version stayed under 1 MB of heap growth in the test and also read fewer columns. When each row must be changed and saved, don't save inside a stream. Buffer a bounded batch instead, and let it go before the next one:

C# TierRecalculation.cs
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;        }    }}

The same loop, run over the 200,000 test orders, stayed flat with ChangeTracker.Clear() and ended at about 113 MB without it. If the change can be written as SQL, ExecuteUpdate avoids loading rows at all.

ApproachMemory grows withFirst rowSave inside the loopGood for
ToListAsync, trackingEvery row and every tracked entityAfter the last rowYesSmall, bounded results you will update
AsAsyncEnumerable, trackingEvery tracked entityRight awayNo, the reader is openRarely the right choice
AsAsyncEnumerable, no tracking or projectionNothing, in principleRight awayNo, the reader is openExports and reports over many rows
Keyset batches with ChangeTracker.Clear()One batchAfter the first batchYes, between batchesUpdating many rows with C# logic

How to apply it in your project

  1. Find unbounded listsLook for ToListAsync and ToArrayAsync on large tables without Take, a key filter or paging, especially in jobs and export endpoints.
  2. Stream reads without trackingSwitch exports and reports to AsAsyncEnumerable with a projection or AsNoTracking(), and write each row as it arrives.
  3. Batch the writesFor row-by-row updates, use keyset batches with SaveChangesAsync and ChangeTracker.Clear() per batch, or ExecuteUpdate when the change fits in SQL.
  4. Check what buffers anywayLook 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.
  • ToListAsync and ToArrayAsync buffer the whole result before you see the first row.
  • AsAsyncEnumerable streams, but only stays flat with AsNoTracking() 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.

📚 المصادر

  1. Efficient Querying: buffering and streaming — EF Core, Microsoft Learn
  2. Asynchronous Programming — EF Core, Microsoft Learn
  3. EntityFrameworkQueryableExtensions.AsAsyncEnumerable — EF Core API reference, Microsoft Learn
  4. Tracking vs. No-Tracking Queries — EF Core, Microsoft Learn
  5. Pagination: keyset pagination — EF Core, Microsoft Learn

التعليقات (0)