Awaiting task completion

There are different ways to wait until the TPL task completes. In the previous code, we used the Task.Wait method. This method blocks the current thread until this task completes. If the task gives a result, the same effect can be achieved when the Task.Result instance property is queried. This is a basic way to coordinate tasks in the program.

When we needed to wait for multiple tasks, we used the Task.WaitAll static method. If we keep aside the optimization and exception handling code, this method will be implemented using the following logic:

var waitedOnTaskList = new List<Task>(tasks.Length); for (int i = tasks.Length - 1; i >= 0; i--) { Task task = tasks[i]; if (!taskIsCompleted) waitedOnTaskList.Add(task); } if (waitedOnTaskList ...

Get Mastering C# Concurrency now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.