Skip to content

Commit 4c64e70

Browse files
Show the Task.WhenEach usage example in "Process asynchronous tasks as they complete" tutorial (#48302)
* Show the example of simplified approach with Task.WhenEach * Move the new section below the CAUTION note * Briefly describe differences between two approaches * Add Task.WhenEach to See also section
1 parent 2196ce4 commit 4c64e70

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

docs/csharp/asynchronous-programming/start-multiple-async-tasks-and-process-them-as-they-complete.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,31 @@ Run the program several times to verify that the downloaded lengths don't always
169169
> [!CAUTION]
170170
> You can use `WhenAny` in a loop, as described in the example, to solve problems that involve a small number of tasks. However, other approaches are more efficient if you have a large number of tasks to process. For more information and examples, see [Processing tasks as they complete](https://devblogs.microsoft.com/pfxteam/processing-tasks-as-they-complete).
171171
172+
## Simplify the approach using `Task.WhenEach`
173+
174+
The `while` loop implemented in `SumPageSizesAsync` method can be simplified using the new <xref:System.Threading.Tasks.Task.WhenEach%2A?displayProperty=nameWithType> method introduced in .NET 9, by calling it in `await foreach` loop.
175+
<br/>Replace the previously implemented `while` loop:
176+
177+
```csharp
178+
while (downloadTasks.Any())
179+
{
180+
Task<int> finishedTask = await Task.WhenAny(downloadTasks);
181+
downloadTasks.Remove(finishedTask);
182+
total += await finishedTask;
183+
}
184+
```
185+
186+
with the simplified `await foreach`:
187+
188+
```csharp
189+
await foreach (Task<int> t in Task.WhenEach(downloadTasks))
190+
{
191+
total += await t;
192+
}
193+
```
194+
195+
This new approach allows to no longer repeatedly call `Task.WhenAny` to manually call a task and remove the one that finishes, because `Task.WhenEach` iterates through task *in an order of their completion*.
196+
172197
## Complete example
173198

174199
The following code is the complete text of the *Program.cs* file for the example.
@@ -178,4 +203,5 @@ The following code is the complete text of the *Program.cs* file for the example
178203
## See also
179204

180205
- <xref:System.Threading.Tasks.Task.WhenAny%2A>
206+
- <xref:System.Threading.Tasks.Task.WhenEach%2A>
181207
- [Asynchronous programming with async and await (C#)](index.md)

0 commit comments

Comments
 (0)