Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Fix an IAsyncEnumerable Loop Silently Running One Item at a Time Even Though You Wrapped It in Task.WhenAll

- 21.10.26 - ErcanOPAK

🔧 The Parallel Loop That Was Never Actually Parallel

An await foreach loop over an IAsyncEnumerable<T> pulls items one at a time by design – each MoveNextAsync call on the underlying async iterator has to complete before the next one starts, since that’s fundamentally how pull-based async streaming works. Wrapping the per-item work inside that loop in Task.WhenAll looks like it should parallelize the processing, but if the tasks are created and awaited sequentially inside the loop body rather than collected into a list first, each iteration’s single-item WhenAll still waits for that one task to finish before the loop can even ask the stream for its next item – the WhenAll call is technically running tasks concurrently, there’s just only ever one task in it at any given moment.

🔎 The Problem

async Task ProcessAllAsync(IAsyncEnumerable<Order> orders)
{
    await foreach (var order in orders)
    {
        // Looks parallel - it's calling Task.WhenAll! - but there's
        // only ever ONE task in the array on any given iteration.
        await Task.WhenAll(ProcessOrderAsync(order));

        // The loop still can't ask for the NEXT order from the
        // stream until this WhenAll (and therefore this one task)
        // completes - so items are still processed strictly one at
        // a time, exactly as if Task.WhenAll was never called at all.
    }
}

// Intended behavior was likely: pull several orders, kick off their
// processing concurrently, and only then wait for that batch as a
// group - which this code never actually does.

✅ Fix: Batch the Items Before You WhenAll Them

  • Explicitly buffer a batch of items from the async stream into a List<T> first (using a fixed batch size, or Chunk-style helper for async streams), THEN call Task.WhenAll once against the full list of per-item tasks for that batch – this is what actually lets several items process concurrently, since every task in the batch is created and running before any of them are awaited.
  • If true full-stream concurrency (not just batches) is the actual goal, use a bounded concurrency pattern like a SemaphoreSlim alongside a collection of in-flight tasks, starting new tasks from the stream as the semaphore permits rather than waiting for one single item’s task to fully complete before pulling the next.
  • Where IAsyncEnumerable’s pull-one-at-a-time nature isn’t actually required (the whole source fits comfortably in memory), consider materializing it to a List<T> with ToListAsync() first, and parallelize over that concrete list instead – this avoids fighting the streaming abstraction’s inherent sequential-pull behavior when the use case never actually needed streaming in the first place.

🚨 Why This Is Dangerous

  • The code compiles cleanly, runs without any exception, and produces entirely correct output – it’s purely a performance bug, with results that look identical whether the items were processed one at a time or genuinely in parallel, which makes it very easy to ship and never notice until someone specifically investigates why a ‘parallelized’ operation takes exactly as long as a fully sequential one would.
  • Because Task.WhenAll genuinely is the correct building block for real concurrency, seeing it present in the code during a review reads as evidence the concurrency was handled correctly – the actual mistake (a single-element array instead of a real batch) is a small, easy detail to miss precisely because the reviewer’s attention is drawn to confirming WhenAll is there at all, not to counting how many tasks it’s actually given.

Task.WhenAll doesn’t make anything run in parallel by itself – it waits for however many tasks you hand it, and handing it exactly one, over and over inside a loop, is just awaiting that one task with extra steps.

— C# Best Practice

Related posts:

C#: Fix a Record's with Expression Silently Skipping a Custom Validation Check Because It Bypasses t...

C#: Fix a Record's with Expression Silently Skipping a Custom Validation Check Because It Bypasses t...

Expression-Bodied Members

Expression-Bodied Members

C#: Use File-Scoped Types to Limit Class Visibility

C#: Use File-Scoped Types to Limit Class Visibility

Views: 4

Post navigation

Photoshop: Fix a Pattern Overlay Layer Style Silently Shifting Position Every Time the Layer Is Resized
C#: Fix a Dictionary Keyed by a Mutable Object Silently Losing Entries After the Key’s Hash Code Changes

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (653)
  • Add Constraint to SQL Table to ensure email contains @ (609)
  • Average of all values in a column that are not zero in SQL (570)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (547)
  • Find numbers with more than two decimal places in SQL (475)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit
  • SQL Server: Fix ROW_NUMBER Ties Reordering Between Identical Runs
  • C#: Fix an Enum HasFlag Returning True for the Zero Value
  • WordPress: Fix Featured Images Vanishing After a CDN Migration
  • Photoshop: Fix Content-Aware Fill Smearing a Repeating Pattern
  • Asp.Net Core: Fix Antiforgery Tokens Rejected Behind a Reverse Proxy

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,055)
  • Get the User Name and Domain Name from an Email Address in SQL (981)
  • How to add default value for Entity Framework migrations for DateTime and Bool (977)
  • Get the First and Last Word from a String or Sentence in SQL (858)
  • How to select distinct rows in a datatable in C# (854)

Recent Posts

  • C#: Fix a ConditionalWeakTable Entry Vanishing Too Soon
  • Docker: Fix a Stale COPY Layer After Editing .dockerignore
  • Photoshop: Fix a Pattern Overlay Scaling Wrong on a High-DPI File
  • SQL Server: Fix a Computed Column Index Skipped by Implicit Cast
  • HTML5: Fix a required Input Inside a Hidden Tab Blocking Submit

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com