Task 有静态方法WaitAll和WaitAny,主要用于等待其他Task完成后做一些事情,先看看其实现部分吧:
public class Task : IThreadPoolWorkItem, IAsyncResult, IDisposable { //Waits for all of the provided Task objects to complete execution. public static void WaitAll(params Task[] tasks) { WaitAll(tasks, Timeout.Infinite); } //Waits for any of the provided Task objects to complete execution.Return The index of the completed task in the tasks array argument. public static int WaitAny(params Task[] tasks) { int waitResult = WaitAny(tasks, Timeout.Infinite); Contract.Assert(tasks.Length == 0 || waitResult != -1, "expected wait to succeed"); return waitResult; } //true if all of the Task instances completed execution within the allotted time; otherwise, false. public static bool WaitAll(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) { if (tasks == null) { throw new ArgumentNullException("tasks"); } if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout"); } Contract.EndContractBlock(); cancellationToken.ThrowIfCancellationRequested(); // early check before we make any allocations List<Exception> exceptions = null; List<Task> waitedOnTaskList = null; List<Task> notificationTasks = null; // If any of the waited-upon tasks end as Faulted or Canceled, set these to true. bool exceptionSeen = false, cancellationSeen = false; bool returnValue = true; // Collects incomplete tasks in "waitedOnTaskList" for (int i = tasks.Length - 1; i >= 0; i--) { Task task = tasks[i]; if (task == null) { throw new ArgumentException(Environment.GetResourceString("Task_WaitMulti_NullTask"), "tasks"); } bool taskIsCompleted = task.IsCompleted; if (!taskIsCompleted) { // try inlining the task only if we have an infinite timeout and an empty cancellation token if (millisecondsTimeout != Timeout.Infinite || cancellationToken.CanBeCanceled) { AddToList(task, ref