Infinite Scroll Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Infinite Scroll runs in O(n) time and O(n) space, in C# as in every other language.
- ✓IAsyncEnumerable<T> from System.Collections.Generic is the shape of a windowed result set, consumed with await foreach and produced by an async iterator that yield returns.
- ✓Return IAsyncEnumerable<Tremor> rather than Task<List<Tremor>> and let the caller decide how much to pull; that is the difference a reviewer looks for between a paginated endpoint and a buffered one.
- ✓The C# trap: An async iterator carries two cancellation tokens and only one is wired by default. Writing await foreach (var t in AfterAsync(...).WithCancellation(ct)) hands ct to the compiler-generated GetAsyncEnumerator(CancellationToken), while the ct parameter inside the method body was bound when AfterAsync was called, which is normally default.
- ✓Each await foreach allocates one state machine object. MoveNextAsync returns ValueTask<bool>, so the common path where the reader already holds a buffered row completes synchronously and allocates nothing; DbDataReader.ReadAsync returns Task<bool>, and that is the one place a per-row allocation can surface.
What Infinite Scroll actually is
Infinite Scroll in C#: what you actually reach for
C# implementation
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Runtime.CompilerServices;
using System.Threading;
namespace Seismo;
public readonly record struct Tremor(long Id, string ObservedAt, double Magnitude);
public static class TremorFeed
{
private const int PageSize = 50;
// [EnumeratorCancellation] is load-bearing: it joins this parameter with the
// token given to the generated GetAsyncEnumerator(CancellationToken).
public static async IAsyncEnumerable<Tremor> AfterAsync(
DbConnection conn, string? afterTs, long afterId,
[EnumeratorCancellation] CancellationToken ct = default)
{
using DbCommand cmd = conn.CreateCommand();
cmd.CommandText =
"SELECT id, observed_at, magnitude FROM tremors " +
"WHERE (observed_at, id) > (@ts, @id) " +
"ORDER BY observed_at, id LIMIT @n";
Add(cmd, "@ts", afterTs ?? "");
Add(cmd, "@id", afterId);
Add(cmd, "@n", PageSize);
// SequentialAccess: do not buffer the row. Columns must then be read
// strictly left to right, which the GetXxx calls below respect.
await using DbDataReader reader =
await cmd.ExecuteReaderAsync(CommandBehavior.SequentialAccess, ct);
while (await reader.ReadAsync(ct))
{
yield return new Tremor(reader.GetInt64(0), reader.GetString(1), reader.GetDouble(2));
}
}
private static void Add(DbCommand cmd, string name, object value)
{
DbParameter p = cmd.CreateParameter();
p.ParameterName = name;
p.Value = value;
cmd.Parameters.Add(p);
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Infinite Scroll?
IAsyncEnumerable<T> from System.Collections.Generic is the shape of a windowed result set, consumed with await foreach and produced by an async iterator that yield returns. The data layer is System.Data.Common: DbConnection, DbCommand.ExecuteReaderAsync taking a CommandBehavior and a token, and DbDataReader.ReadAsync. CommandBehavior itself lives in System.Data. EnumeratorCancellation comes from System.Runtime.CompilerServices. On the way out, JsonSerializer.SerializeAsync accepts an IAsyncEnumerable<T> and writes it as a JSON array incrementally, and WithCancellation and ConfigureAwait on the sequence come from TaskAsyncEnumerableExtensions.
What is the most common C# mistake when implementing Infinite Scroll?
An async iterator carries two cancellation tokens and only one is wired by default. Writing await foreach (var t in AfterAsync(...).WithCancellation(ct)) hands ct to the compiler-generated GetAsyncEnumerator(CancellationToken), while the ct parameter inside the method body was bound when AfterAsync was called, which is normally default. Without [EnumeratorCancellation] on that parameter the two are never joined, so ReadAsync waits on a token nobody will ever cancel and the reader keeps pulling rows after the client disconnected. The compiler does flag this shape as warning CS8425, which is precisely why it ships in builds that treat warnings as noise.
How does Infinite Scroll actually perform in C#?
Each await foreach allocates one state machine object. MoveNextAsync returns ValueTask<bool>, so the common path where the reader already holds a buffered row completes synchronously and allocates nothing; DbDataReader.ReadAsync returns Task<bool>, and that is the one place a per-row allocation can surface. CommandBehavior.SequentialAccess tells the provider not to buffer whole rows, valuable when a column is large, at the cost of having to read columns strictly left to right. readonly record struct keeps rows off the heap until something boxes them. Serialising the sequence directly with SerializeAsync means the page never exists as a List<T> at all. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.