/// <summary> /// 创建 <see cref="T:UnityEngine.TaskExtension.UnityTask" />,取消操作。 /// </summary> /// <returns>取消的任务。</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// </exception> public static UnityTask FromCanceled() { var uTcs = new UnityTaskCompletionSource <int>(); uTcs.SetCanceled(); return(uTcs.Task); }
/// <summary> /// Creates a task that is complete when all of the provided tasks are complete. /// If any of the tasks has an exception, all exceptions raised in the tasks will /// be aggregated into the returned task. Otherwise, if any of the tasks is cancelled, /// the returned task will be cancelled. /// </summary> /// <param name="p_tasks">The tasks to aggregate.</param> /// <returns>A task that is complete when all of the provided tasks are complete.</returns> public static UnityTask WhenAll(IEnumerable <UnityTask> p_tasks) { var taskArr = p_tasks.ToArray(); if (taskArr.Length == 0) { return(UnityTask.FromResult(0)); } var tcs = new UnityTaskCompletionSource <object>(); UnityTask.Factory.ContinueWhenAll(taskArr, _ => { var exceptions = taskArr.Where(p => p.IsFaulted).Select(p => p.Exception).ToArray(); if (exceptions.Length > 0) { tcs.SetException(new System.Threading.Tasks.AggregateException(exceptions)); } else if (taskArr.Any(t => t.IsCanceled)) { tcs.SetCanceled(); } else { tcs.SetResult(0); } }); return(tcs.Task); }
/// <summary> /// 创建一个任务,该任务将在可枚举集合中的所有 <see cref="T:UnityEngine.TaskExtension.UnityTask" /> 对象都完成时完成。 /// </summary> /// <param name="tasks">等待完成的任务。</param> /// <returns>表示所有提供的任务的完成情况的任务。</returns> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="tasks" /> 参数为 <see langword="null" />。 /// </exception> /// <exception cref="T:System.ArgumentException"> /// 此 <paramref name="tasks" /> 集合包含 <see langword="null" /> 任务。 /// </exception> public static UnityTask WhenAll(IEnumerable <UnityTask> tasks) { var taskArray = tasks.ToArray(); if (taskArray.Length == 0) { return(FromResult(0)); } var uTcs = new UnityTaskCompletionSource <object>(); Factory.ContinueWhenAll(taskArray, t => { Exception[] exceptions = taskArray.Where(p => p.IsFaulted).Select(p => p.Exception).ToArray(); if (exceptions.Length > 0) { foreach (var e in exceptions) { Debug.LogError(e); } uTcs.SetException(new System.AggregateException(exceptions)); } else if (taskArray.Any(p => p.IsCanceled)) { uTcs.SetCanceled(); } else { uTcs.SetResult(0); } }); return(uTcs.Task); }