1

I am calling 10 different points from the api in OnInitializedAsync() in Blazor WASM

var tasks = new List<Task>();

var oneTask = OneAsync();
var twoTask = TwoAsync();

tasks.add(oneTask)
tasks.add(twoTask);

await Task.WhenAll(tasks);
var result = await oneTask;

but I suspect it is doing it one by one according to the developer console. I see the call to each point and how long each one takes, shouldn't I run it all at once??

Am I doing something wrong or I don't understand the use of WhenAll?

Angelru
  • 150
  • 1
  • 13
  • How would that single call look like? To what URL would it be to begin with? – GSerg Nov 25 '21 at 07:59
  • I mean run all tasks at once – Angelru Nov 25 '21 at 08:01
  • They are in flight at once. Each will complete in its time. When the last one completes, WhenAll completes. This is not specific to Blazor. – GSerg Nov 25 '21 at 08:02
  • But doesn't it run in parallel? from what I am understanding it is as if there was a foreach and it was making a call for each – Angelru Nov 25 '21 at 08:03
  • They run concurrently. That [does not mean](https://stackoverflow.com/a/34681101/11683) they run on different threads. – GSerg Nov 25 '21 at 08:05
  • `Task.WhenAll` does not change how the tasks were created or scheduled, it simply waits for them all to be completed. You need to look at the code that starts your tasks for indications as to why it (seems to) execute them sequentially. It's certainly not Task.WhenAll's fault. – Lasse V. Karlsen Nov 25 '21 at 08:15
  • I have edited my question with what I am using. – Angelru Nov 25 '21 at 08:22
  • @Angelru You are using it correctly except for the last line where you are repeating the call to `OneAsync` and waiting for it again. Otherwise all tasks in the list run concurrently. – GSerg Nov 25 '21 at 08:27
  • @GSerg I was confused, I have returned to edit. This is how I am using it. – Angelru Nov 25 '21 at 08:33
  • 2
    WhenAll returns the results already: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.whenall?view=net-6.0#System_Threading_Tasks_Task_WhenAll__1_System_Collections_Generic_IEnumerable_System_Threading_Tasks_Task___0___ – Fildor Nov 25 '21 at 08:35
  • @Angelru That's fine then, apart from the minor optimization mentioned by Fildor. – GSerg Nov 25 '21 at 08:43
  • Note that OneAsync and TwoAsync will run synchronously up to the first await that doesn't immediately return a completed result - this may explain your "one by one" results – Hans Kesting Nov 25 '21 at 09:03
  • The console will display results one by one. It cannot do anything else. Even when they all complete at the same time, they will be printed one by one. – GSerg Nov 25 '21 at 09:14

0 Answers0