4
IEnumerable<Task<Request>> requestTasks = CreateRequestTasks();
Task<Trace> traceTask = CreateTraceTask();

var tasks = new List<Task>();
tasks.AddRange(requestTasks);
tasks.Add(traceTask);

await Task.WhenAll(tasks);

How do I get the result from the requestTasks collection?

7
  • foreach(var meTask in tasks) /*get result/*meTask.Result; ? Or even simplier foreach(Task<Request> meTask in requestTasks) meTask.Result; Commented May 16, 2017 at 12:45
  • @m.rogalski Result is a synchronous blocking wait. Commented May 16, 2017 at 12:49
  • But when you awaited all tasks then the result should be available instantly. At least from what I know. Commented May 16, 2017 at 12:50
  • @m.rogalski Yes, but the whole point of async-await is to not block a thread while you wait for a task to finish. Commented May 16, 2017 at 12:51
  • I don't understand your point. He's awaiting these tasks here await Task.WhenAll(tasks); so after these tasks are done he can just use foreach to retrieve results ( which were previously made in task ). Or maybe I'm missing something in here. Commented May 16, 2017 at 12:53

2 Answers 2

11

How do I get the result from the requestTasks collection?

Keep it as a separate (reified) collection:

List<Task<Request>> requestTasks = CreateRequestTasks().ToList();
...
await Task.WhenAll(tasks);
var results = await Task.WhenAll(requestTasks);

Note that the second await Task.WhenAll won't actually do any "asynchronous waiting", because all those tasks are already completed.

Sign up to request clarification or add additional context in comments.

1 Comment

I thought the second await might have caused a second execution of the task. Thanks for the clarification!
2

Since you have to await them all, you can simply write

IEnumerable<Task<Request>> requestTasks = CreateRequestTasks();
Task<Trace> traceTask = CreateTraceTask();

var tasks = await Task.WhenAll(requestTasks);
var trace = await traceTask;

inside an equivalent async block: it may look clearer imho.

Notice also that the above traceTask starts on create (actually this is the same answer since the question itself is a duplicate).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.