Table of Contents

Async buffers and streams

ToAsyncBuffer, ToAsyncBufferStream and ToBufferedAsyncStream read a query at the provider's pace, into pooled chunks, on their own background producer. The connection is released when the last row is read. What happens to the rows after that, and how slowly, is the consumer's business.

They are on the typed views: Map<T>() of a command, and the same view after Skip and Take. Every example on this page is async. The examples are compiled in the samples project, except the two marked "Not compiled by the docs build".

Why: the connection is the scarce thing

The keystone is minimum connection-open time. A connection held while your code serializes a response, calls a web service or writes a file is a connection no one else can use. The producer reads the query into pooled chunks without ever waiting for the consumer, closes the connection, and the consumer works at its own pace afterwards.

The cost is memory. The rows are held, not the connection.

  • An unbounded stream holds a whole result in memory when its consumer is slow, because the producer never waits.
  • A buffer holds everything until it is disposed.

The query is read with the same read as every other terminal: Read() by default, ReadAsync after AsyncReads().

Three panels of paired bars: reader-open time in milliseconds for 10,000 rows. Consumer at 39 ns per row: chunk stream 6.29, no buffer 6.62. At 1 microsecond per row: 6.27 against 16.15. Waiting 20 microseconds per 100 rows: 6.21 against 8.54.

Three panels, each a pair of bars that start at zero, on one scale: how long the reader is held open for a result of 10,000 rows, as the consumer gets slower. The left bar of each pair is ToAsyncBufferStream; the right bar is no buffer, the consumer working inside the read. At 39 ns per row the pair is 6.29 and 6.62 ms. At 1 µs per row it is 6.27 and 16.15 ms. With a 20 µs wait per 100 rows it is 6.21 and 8.54 ms. The chunk stream holds the reader the same time however slow the consumer is; without a buffer the reader is held as long as the consumer takes. The source is the library's unpublished pooled-buffer benchmark round: a synthetic provider on net11 with a 50 µs refill every 100 rows, one run. It is not a real database.

The three terminals

Terminal Returns Starts Use it for
ToAsyncBuffer PooledBuffer<T> At the call, on its own producer, even if nobody reads yet A result you hand to another layer, or work with for a while: a reusable list, with an indexer
ToAsyncBufferStream IAsyncEnumerable<ReadOnlyMemory<T>>, one chunk per step At the first MoveNextAsync. Single-use Sequential, read-only access to the rows without copying them twice
ToBufferedAsyncStream IAsyncEnumerable<T>, one row per step At the first MoveNextAsync. Single-use The same, made easy: await foreach and System.Linq.Async work as they do on any stream

ToAsyncBuffer returns at once. (A cancellation token that is already cancelled starts nothing.) The read may finish before anyone asks for the rows. The buffer is not readable while it fills: its rows are reached through Items, once the read is done. To read while the query is still running, use one of the streams. If the command is on a connection you opened yourself, do not use that connection for anything else until the read has finished: the producer reads on it from the call (ToAsyncBuffer) or from the first step (the streams).

The streams do nothing until the first MoveNextAsync, and they can be enumerated once. A second GetAsyncEnumerator on the chunk stream throws InvalidOperationException; on the element stream the same exception comes at the first MoveNextAsync.

The same terminals are on a view with Skip and Take:

public static async Task<int[]> SkipTakeAsync(
    IDbConnectionFactory<SqliteConnection> connectionFactory,
    CancellationToken cancellationToken)
{
    // The same terminals are on every typed view.
    await using PooledBuffer<Post> buffer = connectionFactory
        .Command("select * from posts order by id")
        .Map<Post>()
        .Skip(1).Take(2)
        .ToAsyncBuffer(cancellationToken);

    PooledArray<Post> posts = await buffer.Items;
    return [.. posts.Select(static p => p.Id)];
}

The controller story

The use case that shaped ToAsyncBuffer is a data layer that hands rows up to a layer that does not know about the database. A command factory method returns PooledBuffer<T>:

// The data layer: it starts the read and returns at once.
// Nothing here waits for the rows.
public static PooledBuffer<Post> LatestPosts(
    IDbConnectionFactory<SqliteConnection> connectionFactory,
    CancellationToken cancellationToken)
    => connectionFactory
        .Command("select * from posts order by id")
        .Map<Post>()
        .ToAsyncBuffer(cancellationToken);

The method returns at once and the read is already running. The layer above, a controller say, awaits the rows when it needs them, serializes them and disposes the buffer:

// The layer above: it awaits the rows when it needs them,
// serializes them, and disposes the buffer.
public static async Task<string> RenderPostsAsync(
    IDbConnectionFactory<SqliteConnection> connectionFactory,
    CancellationToken cancellationToken)
{
    await using PooledBuffer<Post> buffer
        = LatestPosts(connectionFactory, cancellationToken);

    // The read began in the call above and runs on its own
    // producer, so other work can happen here.
    PooledArray<Post> posts = await buffer.Items;

    await using MemoryStream json = new();
    await JsonSerializer.SerializeAsync<IReadOnlyList<Post>>(
        json,
        posts,
        cancellationToken: cancellationToken);

    return Encoding.UTF8.GetString(json.ToArray());
}

The connection was released when the read ended, however long the serialization took. Everything here is async: await using for the buffer, await buffer.Items for the rows, and no synchronous wait anywhere. Do not block on Items.Result. The producer runs on the ambient task scheduler, so blocking the one thread of a single-thread scheduler (a UI thread, an old synchronization context) can deadlock it.

The Items view

Items is a Task<PooledArray<T>>: the same task on every access, and the view is built only if someone asks. A PooledArray<T> is a read-only list over the pooled arrays:

  • It is an IReadOnlyList<T>, and an explicit read-only ICollection<T> (Add, Clear and Remove throw NotSupportedException).
  • Count and the indexer are O(1).
  • foreach binds to a struct enumerator.
  • LINQ's ToArray and ToList and the List<T> constructor see the count, and copy it one array at a time.
public static async Task<ItemsFacts> ItemsViewAsync(
    IDbConnectionFactory<SqliteConnection> connectionFactory,
    CancellationToken cancellationToken)
{
    await using PooledBuffer<Post> buffer
        = LatestPosts(connectionFactory, cancellationToken);
    PooledArray<Post> posts = await buffer.Items;

    int count = posts.Count;
    Post third = posts[2];

    // foreach uses a struct enumerator.
    int idSum = 0;
    foreach (Post post in posts)
        idSum += post.Id;

    // LINQ knows the count, so this copies array by array.
    Post[] copy = posts.ToArray();

    return new(count, third.Id, idSum, copy.Length);
}

A read that finds no rows completes Items with PooledArray<T>.Empty, which needs no disposing and never throws ObjectDisposedException.

To test code that returns a buffer, without a database, build one from rows you already have: PooledBuffer<Post>.From(rows) copies them into one array rented from the shared pool (From(rows, pool, clearOnReturn) takes a pool you choose), nothing runs in the background, Items is complete at once, and disposing it sends the array back to the pool (through the cleanup queue for 128 KB or more of rows that must be cleared). No rows give PooledArray<T>.Empty.

Items faults with the read's exception. It is cancelled when the read ended with an OperationCanceledException of any origin, or when the buffer was disposed first. Reading Items after the buffer is disposed throws ObjectDisposedException; a task you already hold that is still pending is cancelled. See Cancellation and disposal.

The view is valid until it is disposed. Disposing it disposes the buffer it came from and returns the arrays to the pool. After that every member of the view except Dispose throws ObjectDisposedException, an enumeration in progress included. Disposing again does nothing. Disposing the buffer while the read is still running cancels the query. See Pooled memory for when the arrays are cleared.

Lifetime and ownership

A buffer is a lease of pooled arrays, and a lease has rules:

  • One owner disposes. Whoever ends the use of the rows disposes the buffer, once. The PooledArray<T> from Items is the same lease, so disposing the view disposes the buffer. Do not hand the view to a second owner that also disposes it, and do not dispose while something else still reads it.
  • A lazy query runs when it is enumerated. Where, Select and the rest of LINQ run nothing when you call them. If the query is enumerated after the buffer is disposed, it reads arrays that are back in the pool, and the view throws ObjectDisposedException. Finish the query (ToList(), ToArray()) before the buffer goes.
  • Copy out to keep the rows longer. ToArray() or ToList() on the view copies the rows. The copy belongs to you and outlives the buffer.
  • One thread at a time. Do not use the view from another thread while something may dispose it. The view checks that it is alive before each read, but a check is not a lock: a dispose on another thread can land just after it, with the arrays on their way back to the pool.
  • A buffer that is never disposed is not a leak, but it costs the pool. There is no finalizer. The arrays stay with the buffer until the garbage collector takes it, and the pool never gets them back. The cost is the allocations the pool would have saved. This includes await LatestPosts(...).Items when Items faults or is cancelled: you never receive the view, so nothing disposes the buffer, and its arrays wait for the garbage collector.

To shape the rows as they arrive, use async LINQ over the stream and return it: no async, no await, no using. Filter in the SQL; shape in C#. The work overlaps the read, only what you keep is held, and there is nothing to dispose. It is in the box on net10 and later; net472 and netstandard need the System.Linq.Async package.

// The SQL filters; the C# shapes. No async, await or using:
// the read starts when the caller enumerates the stream.
public static IAsyncEnumerable<string> PostLabelsAsync(
    IDbConnectionFactory<SqliteConnection> connectionFactory,
    int author,
    CancellationToken cancellationToken)
    => connectionFactory
        .Command("select * from posts where author = @author order by id")
        .AddParam(author)
        .Map<Post>()
        .ToBufferedAsyncStream(cancellationToken)
        .Select(static post => $"{post.Id}: {post.Title}");

To keep every row, call ToArrayAsync or ToListAsync on the query directly: they collect the rows for you, and there is no buffer to dispose.

Take the buffer, or its Items view, when you need the whole set at once: Count, the indexer, several passes, or handing it to a serializer. Finish any LINQ query over the view before the view is disposed:

// A LINQ query over the view is lazy: it runs when it is
// enumerated. Finish it before the buffer is disposed.
public static async Task<List<string>> FinishQueryAsync(
    IDbConnectionFactory<SqliteConnection> connectionFactory,
    CancellationToken cancellationToken)
{
    // Disposing the view disposes the buffer it came from.
    using PooledArray<Post> posts
        = await LatestPosts(connectionFactory, cancellationToken).Items;

    // ToList() runs the query now, while the view is alive.
    return posts
        .Select(static post => $"{post.Id}: {post.Title}")
        .ToList();
}

The mistake to avoid is a query that has not run when the buffer is disposed. This one throws:

// The mistake: the query has not run when the buffer is
// disposed, so it runs on arrays that are already back in the pool.
public static async Task<bool> LazyAfterDisposeAsync(
    IDbConnectionFactory<SqliteConnection> connectionFactory,
    CancellationToken cancellationToken)
{
    IEnumerable<int> ids;
    using (PooledArray<Post> posts
        = await LatestPosts(connectionFactory, cancellationToken).Items)
    {
        ids = posts.Select(static post => post.Id);
    }

    try
    {
        _ = ids.ToList();
        return false;
    }
    catch (ObjectDisposedException)
    {
        return true;
    }
}

Returning it from a controller

The controller above serializes the rows itself, inside the method, so it can dispose the buffer in the same method. The other way is to hand the rows to the framework and let the framework serialize them after the action has returned. The buffer must then outlive the action, and the framework has to dispose it, not your method.

The pattern is to register the buffer with the response, and then return the rows:

[ApiController]
[Route("posts")]
public class PostsController(
    IDbConnectionFactory<SqliteConnection> connectionFactory)
    : ControllerBase
{
    [HttpGet]
    public Task<PooledArray<Post>> GetAsync()
    {
        // LatestPosts is the data-layer method shown above (call it as you
        // have named it): the read starts here.
        PooledBuffer<Post> buffer = LatestPosts(
            connectionFactory,
            HttpContext.RequestAborted);

        // The framework disposes it when the request is over.
        Response.RegisterForDispose(buffer);

        // The framework awaits the rows, then writes them.
        // A PooledArray<Post> is an IReadOnlyList<Post>:
        // System.Text.Json writes it as a JSON array.
        return buffer.Items;
    }
}

What was observed on ASP.NET Core 11.0.0 against SQLite:

  • The response is 200 with a JSON array of the rows, equal to the array the same query gives with ToListAsync. The action returns Items without awaiting it, so it declares Task<PooledArray<Post>>. An async action that returns await buffer.Items can declare IReadOnlyList<Post> instead; the JSON is the same.
  • Every array went back to the pool once the request was over.
  • HttpResponse.RegisterForDispose and HttpResponse.RegisterForDisposeAsync both exist. A PooledBuffer<T> is both IDisposable and IAsyncDisposable, and the framework disposed it with DisposeAsync whichever of the two was used, so RegisterForDispose is enough.
  • Register the buffer before you return Items. A client abort cancels HttpContext.RequestAborted, which cancels the query. On Kestrel the buffer was still disposed after an abort, and an object registered the same way was disposed when the action threw.
Note

The form above, which returns the task, was checked on TestServer; the Kestrel observations were made with an action that awaited Items. TestServer did not dispose what the request had registered when the action threw or the client aborted before the response started; Kestrel did. A test of your own controller that counts the arrays that come back sees them only on a successful request, or on a real server.

The trap: dispose before the framework serializes

The tempting version disposes the buffer in the action, the way the controller above does:

// Not compiled by the docs build. Do not do this.
[HttpGet]
public async Task<IReadOnlyList<Post>> GetAsync()
{
	await using PooledBuffer<Post> buffer = LatestPosts(
		connectionFactory,
		HttpContext.RequestAborted);

	// The buffer is disposed as this method returns,
	// before the framework has serialized anything.
	return await buffer.Items;
}

The framework serializes the rows after the action has returned, and by then the buffer is disposed. System.Text.Json calls the view's enumerator and gets ObjectDisposedException. The response had not started, so on Kestrel it is a 500 with an empty body and the exception in the log; on TestServer the exception reaches the caller. The body is empty, not partial. Nothing in the compiler stops it, so it is the first thing to look for in a code review.

A very large result: return the stream

A buffer holds the whole result until the request is over. For a very large result, return the stream and let the framework walk it:

// Not compiled by the docs build. Checked against ASP.NET Core 11.0.0.
[HttpGet("stream")]
public IAsyncEnumerable<Post> StreamAsync()
	=> connectionFactory
		.Command("select * from posts order by id")
		.Map<Post>()
		.ToBufferedAsyncStream(HttpContext.RequestAborted);

There is nothing to register: the framework enumerates the stream and disposes the enumerator, which returns every array still queued. What was observed:

  • System.Text.Json wrote it as a JSON array, equal to the list the same query gives, with status 200.
  • The response was streamed: it started before the last row was read.
  • Every array went back to the pool, including when the client aborted in the middle of the body or before reading any of it. An abort stopped the query early.

A stream still reads ahead without waiting for the client, as described above, where a slow consumer is measured; a slow HTTP client was not measured. The rows it has not taken yet wait in memory.

The streams

ToAsyncBufferStream yields one chunk at a time as a ReadOnlyMemory<T>. A chunk holds exactly the rows of one chunk and is valid until the next step of the loop, when its array goes back to the pool. Copy what you keep, and do not collect the chunks themselves (with ToListAsync or Buffer, say): nothing guards a memory held longer.

public static async Task<List<int>> ChunkStreamAsync(
    IDbConnectionFactory<SqliteConnection> connectionFactory,
    CancellationToken cancellationToken)
{
    List<int> ids = [];

    IAsyncEnumerable<ReadOnlyMemory<Post>> chunks = connectionFactory
        .Command("select * from posts order by id")
        .Map<Post>()
        .ToAsyncBufferStream(cancellationToken);

    // Each chunk is valid until the next step of the loop:
    // copy what you keep.
    await foreach (ReadOnlyMemory<Post> chunk in chunks)
    {
        foreach (Post post in chunk.Span)
            ids.Add(post.Id);
    }

    return ids;
}

ToBufferedAsyncStream flattens each chunk into its rows. Each row is copied out before it is yielded, so a row has no lifetime to mind. A break out of await foreach disposes the enumerator, which cancels the query and returns every array still queued.

public static async Task<(List<int> Ids, bool SecondThrew)>
    ElementStreamAsync(
        IDbConnectionFactory<SqliteConnection> connectionFactory,
        CancellationToken cancellationToken)
{
    List<int> ids = [];

    IAsyncEnumerable<Post> posts = connectionFactory
        .Command("select * from posts order by id")
        .Map<Post>()
        .ToBufferedAsyncStream(cancellationToken);

    await foreach (Post post in posts)
        ids.Add(post.Id);

    // The stream is single-use: this throws.
    bool secondThrew = false;
    try
    {
        await foreach (Post post in posts)
            ids.Add(post.Id);
    }
    catch (InvalidOperationException)
    {
        secondThrew = true;
    }

    return (ids, secondThrew);
}

Always dispose the enumerator, which await foreach does. An enumerator that is abandoned gives nothing back: the producer keeps reading the whole query into its unbounded queue, so the connection is held until that read ends.

Pooled memory

The rows of a buffer or a stream, and the chunks a collector (ToListAsync, ToArrayAsync and the rest) reads into before it copies the result once, live in arrays rented from a pool. By default the pool is ArrayPool<T>.Shared. An array goes back to its pool when the call, the buffer or the stream is done, and what is in it then is the question this section answers.

The measurements behind these choices (which pool, how rows are cleared, and where) are on Pooling and clearing.

What is cleared

A pooled array that goes back with rows in it keeps them reachable while it sits in the pool, and any other code in the process can rent the same array next. So ODX decides, for every array it rents, with one rule:

  1. Rows that hold references are always cleared. A class, a string, a struct that contains either: the used rows are cleared before the array goes back, so a pooled array never keeps a row alive. Nothing turns this off.
  2. Rows with no references are cleared when asked. An int or a plain struct holds nothing to keep alive, so clearing them costs time for no gain unless the values are sensitive. The default is not to clear them.

Two settings raise that default for rows with no references, and the more specific one wins.

The app-wide switch Open.Database.Extensions.ClearPooledArrays clears every array ODX rents, value rows included, for every query that does not say otherwise. It is off by default and is read once, so set it before the first query. The way to set it is in the application's project file, which puts it in runtimeconfig.json, where an operator can also change it:

<ItemGroup>
  <RuntimeHostConfigurationOption Include="Open.Database.Extensions.ClearPooledArrays" Value="true" />
</ItemGroup>

Or in code, before the first query: AppContext.SetSwitch("Open.Database.Extensions.ClearPooledArrays", true).

UsePool(pool, clearOnReturn) decides for one query. It goes after Map, and both arguments are required, so the choice is always visible at the call. Write the second by name:

public static async Task<int> ClearingSharedAsync(
    IDbConnectionFactory<SqliteConnection> connectionFactory,
    CancellationToken cancellationToken)
{
    // The shared pool, and the rows are scrubbed as they go back.
    await using PooledBuffer<int> buffer = connectionFactory
        .Command("select id from posts order by id")
        .Map<int>()
        .UsePool(ArrayPool<int>.Shared, clearOnReturn: true)
        .ToAsyncBuffer(cancellationToken);

    return (await buffer.Items).Count;
}

An explicit clearOnReturn: true clears value rows whatever the switch says. An explicit clearOnReturn: false keeps them as they are, also when the switch is on: this is the opt-out, and it is per query. It cannot lower the floor: clear controls rows with no references, and rows that hold references are always cleared.

Your own pool

UsePool takes any ArrayPool<T>. Every pooling terminal of that query rents from it: the collectors and the three buffer terminals. ArrayPool<T>.Shared is what a query without UsePool uses.

static MappedQuery<Post> Query(
    IDbConnectionFactory<SqliteConnection> connectionFactory)
    => connectionFactory
        .Command("select * from posts order by id")
        .Map<Post>();

public static async Task<int[]> OverloadsAsync(
    IDbConnectionFactory<SqliteConnection> connectionFactory,
    ArrayPool<Post> pool,
    CancellationToken cancellationToken)
{
    // The shared pool is the default.
    await using PooledBuffer<Post> shared = Query(connectionFactory)
        .ToAsyncBuffer(cancellationToken);

    // Your own pool, chosen after Map. Both arguments are required.
    await using PooledBuffer<Post> own = Query(connectionFactory)
        .UsePool(pool, clearOnReturn: false)
        .ToAsyncBuffer(cancellationToken);

    // The same, and the rows are cleared as the arrays go back.
    await using PooledBuffer<Post> scrubbed = Query(connectionFactory)
        .UsePool(pool, clearOnReturn: true)
        .ToAsyncBuffer(cancellationToken);

    return
    [
        (await shared.Items).Count,
        (await own.Items).Count,
        (await scrubbed.Items).Count,
    ];
}

The rules of a pool of your own:

  • It is yours. ODX rents from it and gives back to it, and never disposes it. A null pool throws ArgumentNullException at the call.
  • It decides how long its arrays are. ODX takes what the pool gives, uses the whole array, writes only the rows it has, and clears only those, not the rest. A pool that gives a shorter array than was asked for makes the read throw InvalidOperationException; that array, and every array before it, is given back.
  • It may round up. A pool that returns a longer array than asked for is fine, as ArrayPool<T>.Shared does; the extra room is used, and only the rows are copied.
  • Returning an array must not throw. If it does, every other array is still returned, and the first exception is thrown after the last. In the cleanup queue (below) a return that throws is swallowed and costs only that array.

The samples use a pool of their own to check the claims on this page:

// A pool of your own. This one counts what it rents and what comes
// back, and how many returned arrays still held rows.
public sealed class CountingPool<T> : ArrayPool<T>
{
    int _rented;
    int _returned;
    int _dirty;

    public int Rented => Volatile.Read(ref _rented);
    public int Returned => Volatile.Read(ref _returned);
    public int Dirty => Volatile.Read(ref _dirty);

    public override T[] Rent(int minimumLength)
    {
        Interlocked.Increment(ref _rented);
        return new T[Math.Max(minimumLength, 1)];
    }

    public override void Return(T[] array, bool clearArray = false)
    {
        // What a pool does with the flag.
        if (clearArray)
        {
            Array.Clear(array);
        }

        if (Array.Exists(
            array,
            static item => !EqualityComparer<T>.Default.Equals(item, default)))
        {
            Interlocked.Increment(ref _dirty);
        }

        Interlocked.Increment(ref _returned);
    }
}
public static async Task ClearingAsync(
    IDbConnectionFactory<SqliteConnection> connectionFactory,
    ArrayPool<int> pool,
    bool clearOnReturn,
    CancellationToken cancellationToken)
{
    // A row with no references (an int) is cleared only when asked:
    // the pool is yours, the clear is stated by name.
    await using PooledBuffer<int> buffer = connectionFactory
        .Command("select id from posts order by id")
        .Map<int>()
        .UsePool(pool, clearOnReturn: clearOnReturn)
        .ToAsyncBuffer(cancellationToken);

    PooledArray<int> ids = await buffer.Items;

    // ... use the rows. The clear runs as the arrays go back, when the
    // buffer is disposed.
    _ = ids.Count;
}

When the clear happens

  • What is cleared is the rows that were written, never the rest of a longer array. When every slot of an array was written, the pool is asked to clear it (Return(array, clearArray: true)); otherwise only the written slots are cleared and the array goes back without the flag.
  • For a buffer, the clear takes effect when the buffer, or its PooledArray<T> view, is disposed. For a stream, as each chunk goes back: at the next step, or when the enumeration ends or is disposed. For a collector, when the call ends, after the result is built.
  • A chunk of 128 KB or more of rows, value rows included, is cleared and returned on one background loop, so neither the read nor the consumer waits. A smaller chunk is cleared where it is released.
  • If 10,240 clears are ever waiting (a stalled custom pool, or an extreme burst), the next chunk is cleared and returned by the code that releases it, as a small one is. A dirty array never reaches a pool, and none is left behind with its rows.
  • A custom pool's Return should not block: the loop is shared by every pool.

Cancellation and disposal

  • Two sources, one token. The caller's token and the dispose are combined, so either one cancels the database read itself, not only the loop around it.
  • Our own cancel is swallowed. A cancel caused by disposing the buffer, or the stream's enumerator, is not reported: you asked for it. The read ends quietly, and an Items task you were already awaiting is cancelled.
  • Yours is delivered. The caller's own cancel, or a fault in the read, is delivered: to a stream after the rows that were already read, and to a buffer through Items. A stream's next step throws it after the chunks that were already delivered. Items is cancelled or faulted instead of producing a view.
  • DisposeAsync waits for the producer, with no timeout. It cancels a running read, waits until the producer has stopped, and returns the arrays (a large chunk that is to be cleared goes to the cleanup queue, so it is back in the pool shortly after DisposeAsync completes). A provider that ignores cancellation delays it by the call in progress. After that, the producer stops at the next chunk boundary at the latest. The synchronous Dispose does not wait. It cancels and returns at once. If the read is still running, the producer returns the arrays when it exits; if it had finished, Dispose returns them itself.
public static async Task<bool> CallerCancelAsync(
    IDbConnectionFactory<SqliteConnection> connectionFactory)
{
    // The caller's own cancel is delivered, not swallowed.
    // Here the token is cancelled before the call, so nothing
    // starts; a cancel during the read ends it the same way.
    using CancellationTokenSource cts = new();
    await cts.CancelAsync();

    await using PooledBuffer<Post> buffer = connectionFactory
        .Command("select * from posts order by id")
        .Map<Post>()
        .ToAsyncBuffer(cts.Token);

    try
    {
        await buffer.Items;
        return false;
    }
    catch (OperationCanceledException)
    {
        return true;
    }
}
public static async Task<bool> DisposeEarlyAsync(
    IDbConnectionFactory<SqliteConnection> connectionFactory,
    ArrayPool<Post> pool,
    CancellationToken cancellationToken)
{
    PooledBuffer<Post> buffer = Query(connectionFactory)
        .UsePool(pool, clearOnReturn: false)
        .ToAsyncBuffer(cancellationToken);

    // Cancels the read if it is still running, waits for the
    // producer to stop, and returns the arrays to the pool.
    await buffer.DisposeAsync();

    // A disposed buffer has no Items.
    try
    {
        _ = buffer.Items;
        return false;
    }
    catch (ObjectDisposedException)
    {
        return true;
    }
}

Memory shape

Chunks start at 16 rows and double: 16, 32, 64 and so on. A buffer keeps doubling, and never moves a row once it is written. A stream stops doubling at 4,096 rows, so a long result is read in chunks of at most 4,096.

What it costs

The numbers come from a synthetic provider on net11, not from a real database, and they are one run each. The figure and the simulated-link numbers were measured with AsyncReads() on for every variant, so the refill waits are real awaits; with the default Read() the buffer and ToArrayAsync held the reader 5.26 and 5.23 ms at a 50 µs refill. The refill timer busy-waits on one of the four cores the run used, so the overlap ran on about three.

  • Reader-open time stays flat as the consumer slows. For the chunk stream at 10,000 rows it was 6.29, 6.27 and 6.21 ms for the three consumers in the figure above.
  • On a simulated link it is within a few percent of ToArrayAsync. At a 50 µs refill the buffer held the reader 6.27 ms and ToArrayAsync 6.29 ms.
  • At zero latency and 10,000 rows, dumping a result into a buffer holds the reader about 22% longer than ToArrayAsync: 225 against 185 µs. The buffer pays that to be able to hand the rows to someone else.

When to use something else

When the rows are only read or written once, the buffer is the default, whatever the size: the rows exist once and no list is built. It is not faster: see What it costs.

To keep or change the rows, use ToArrayAsync or ToListAsync: the copy is yours and there is nothing to dispose.

// An array that is yours to keep or change. Nothing to dispose.
public static ValueTask<Post[]> PostsToKeepAsync(
    IDbConnectionFactory<SqliteConnection> connectionFactory,
    CancellationToken cancellationToken)
    => connectionFactory
        .Command("select * from posts order by id")
        .Map<Post>()
        .ToArrayAsync(cancellationToken);

To read a query while a consumer works, use the buffer streams: the connection is released as soon as the last row is read. See Channels and Dataflow.

Sources

Claim Value Run
Reader-open time, chunk stream, 10,000 rows 6.29, 6.27 and 6.21 ms at 39 ns per row, 1 µs per row and a 20 µs wait per 100 rows the library's unpublished pooled-buffer benchmark round, synthetic provider, net11, a 50 µs refill every 100 rows; one run
Reader-open time, no buffer (the figure) 6.62, 16.15 and 8.54 ms for the same consumers same
Buffer against ToArrayAsync, simulated link 6.27 and 6.29 ms, at a 50 µs refill every 100 rows same round, same provider; one run
Buffer against ToArrayAsync, zero latency 225 and 185 µs at 10,000 rows (about 22% longer) same round, same provider; one run
The controller checks: status, body, pool balance, abort RegisterForDispose, a dispose before serialization, a returned stream, a client abort: 5,000 rows, and 1,000,000 rows for the aborts ASP.NET Core 11.0.0 with TestServer and with Kestrel on loopback, Microsoft.Data.Sqlite on a file database, a counting MemoryPool<T>; one run or a few. A scratch project, not part of the docs build
Chunk sizes, the cleanup queue, the single-use rule 16 doubling to 4,096 for a stream; 10,240 waiting clears the library source (ChunkSizing, RecycleBin, ChunkStream); not a measurement