Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Infinite Scroll Implementation in C#

14 min readintermediate
Website QA and SEO audits

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 replaces the page-number control with a trigger: as the reader nears the end of what has been rendered, the next slice is fetched and appended. Two decisions determine whether this is smooth or wretched, and neither is the spinner. The first is how the next slice is asked for. OFFSET re-walks and discards every row before the window, so page 400 costs four hundred times page 1, and a row inserted while the reader is scrolling shifts every boundary, which surfaces as duplicated rows and silently skipped ones. Keyset pagination, also called cursor pagination, instead sends the sort key of the last row already delivered and asks for rows strictly after it. That turns the read into one index descent costing the same on page 400 as on page 1, and it stays correct while the underlying set changes beneath it. The second is how arrival is detected. Sampling scroll offsets runs work on every scroll event, on the thread that also has to paint. The better shape is a sentinel element watched asynchronously, so the platform reports the crossing rather than the page interrogating it. Then the part everyone forgets: the rendered list only grows, and every appended node is memory the reader will never scroll back to. The eight languages split three ways. Two are the browser and own the sentinel, the scroll box and the growing node list directly. One is a native client whose list is lazy by construction, which turns the trigger into a view-lifecycle question. The other five sit on the server end of the same contract, where infinite means a result set walked in bounded windows rather than materialised, and they disagree sharply about who owns the database cursor and when it is released. One of the five has no standard library answer at all and expresses the window as a borrow the compiler refuses to let escape.

Infinite Scroll in C#: what you actually reach for

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.

C# implementation

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. await using goes on the connection and the reader, plain using on the command. Library code chains .WithCancellation(ct).ConfigureAwait(false) at the await foreach. Rows are readonly record structs so equality and immutability come free. And parameters are always DbParameter objects, never interpolated, which the analyzers enforce anyway.
csharp
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 Free

The C#-specific 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. 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.

Performance in C#, beyond the O(n)

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. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Infinite Scroll between languages.

Real-World Applications

Infinite Scroll is used extensively in production software: web frameworks, content management systems, API gateways, and SPA architectures implement this pattern for handling HTTP requests and rendering. In C#, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Infinite Scroll helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Infinite Scroll appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Infinite Scroll over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Infinite Scroll to build pattern recognition. In C#, demonstrate proficiency with LINQ and async patterns to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic C# code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Before paying for Replit, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.