ReubenBond/hanbaobao-web

Why are the tasks being awaited in Search.cs?

drakeforte5 opened this issue · 2 comments

Just wanted to clarify something line 90 of Search.cs:

Why are you awaiting again when Task.WhenAll(tasks) already awaited?

        // Wait for all calls to complete
        await Task.WhenAll(tasks);

        _// Collect the results into a list to return
        var results = new List<TermDefinition>(tasks.Count);
        foreach (var task in tasks)
        {
          //Why wait again?
            **results.Add(await task);**
        }_

Shouldn't it be:
var results = await Task.WhenAll(tasks);

results is already an IEnumerable which is the return of the awaited tasks.

Thanks.

It awaits the task to get the result from within. You have Task<TermDefinition> and you want the TermDefinition inside it.
There are two options:

  • await task
  • task.Result / task.GetAwaiter().GetResult()

The second choice would be slightly more efficient than awaiting it, but the await will complete synchronously - it won't actually wait (since the task has already completed, as you noted)

Thanks.