Skip to content

Commit e03af3f

Browse files
Show the example of simplified approach with Task.WhenEach
1 parent 965e56e commit e03af3f

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

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

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,29 @@ For any given URL, the method will use the `client` instance provided to get the
166166

167167
Run the program several times to verify that the downloaded lengths don't always appear in the same order.
168168

169+
## Simplify the approach using `Task.WhenEach`
170+
171+
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.
172+
<br/>Replace the previously implemented `while` loop:
173+
174+
```csharp
175+
while (downloadTasks.Any())
176+
{
177+
Task<int> finishedTask = await Task.WhenAny(downloadTasks);
178+
downloadTasks.Remove(finishedTask);
179+
total += await finishedTask;
180+
}
181+
```
182+
183+
with the simplified `await foreach`:
184+
185+
```csharp
186+
await foreach (Task<int> t in Task.WhenEach(downloadTasks))
187+
{
188+
total += await t;
189+
}
190+
```
191+
169192
> [!CAUTION]
170193
> 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).
171194

0 commit comments

Comments
 (0)