3
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?

Naeem Sarfraz
  • 7,360
  • 5
  • 37
  • 63
  • `foreach(var meTask in tasks) /*get result/*meTask.Result;` ? Or even simplier `foreach(Task meTask in requestTasks) meTask.Result;` – mrogal.ski May 16 '17 at 12:45
  • @m.rogalski `Result` is a synchronous blocking wait. – juharr May 16 '17 at 12:49
  • But when you awaited all tasks then the result should be available instantly. At least from what I know. – mrogal.ski May 16 '17 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. – juharr May 16 '17 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. – mrogal.ski May 16 '17 at 12:53
  • This answer http://stackoverflow.com/a/17197786/40986 set me in the right direction. But was unsure if using awaiting the task again meant the request is executed again. Appears not to – Naeem Sarfraz May 16 '17 at 12:57
  • Possible duplicate of [Awaiting multiple Tasks with different results](http://stackoverflow.com/questions/17197699/awaiting-multiple-tasks-with-different-results) –  May 17 '17 at 07:06

2 Answers2

10

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.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
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).

Community
  • 1
  • 1