C# Task WhenAny和WhenAll 以及TaskFactory 的ContinueWhenAny和ContinueWhenAll的实现
个人感觉Task 的WaitAny和WhenAny以及TaskFactory 的ContinueWhenAny有相似的地方,而WaitAll和WhenAll以及TaskFactory 的ContinueWhenAll也是相同,但是WaitAny和WhenAny的返回值有所不同。我们首先来看看Task WhenAny和WhenAll 的实现吧,
public class Task : IThreadPoolWorkItem, IAsyncResult, IDisposable
{
//Creates a task that will complete when any of the supplied tasks have completed.
public static Task<Task> WhenAny(IEnumerable<Task> tasks)
{
if (tasks == null) throw new ArgumentNullException("tasks");
Contract.EndContractBlock();
List<Task> taskList = new List<Task>();
foreach (Task task in tasks)
{
if (task == null) throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks");
taskList.Add(task);
}
if (taskList.Count == )
{
throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"), "tasks");
}
// Previously implemented CommonCWAnyLogic() can handle the rest
return TaskFactory.CommonCWAnyLogic(taskList);
} //Creates a task that will complete when all of the supplied tasks have completed.
public static Task<TResult[]> WhenAll<TResult>(params Task<TResult>[] tasks)
{
if (tasks == null) throw new ArgumentNullException("tasks");
Contract.EndContractBlock(); int taskCount = tasks.Length;
if (taskCount == ) return InternalWhenAll<TResult>(tasks); // small optimization in the case of an empty task array Task<TResult>[] tasksCopy = new Task<TResult>[taskCount];
for (int i = ; i < taskCount; i++)
{
Task<TResult> task = tasks[i];
if (task == null) throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), "tasks");
tasksCopy[i] = task;
}
return InternalWhenAll<TResult>(tasksCopy);
} private static Task<TResult[]> InternalWhenAll<TResult>(Task<TResult>[] tasks)
{
Contract.Requires(tasks != null, "Expected a non-null tasks array");
return (tasks.Length == ) ? new Task<TResult[]>(false, new TResult[], TaskCreationOptions.None, default(CancellationToken)) : new WhenAllPromise<TResult>(tasks);
} private sealed class WhenAllPromise<T> : Task<T[]>, ITaskCompletionAction
{
private readonly Task<T>[] m_tasks;
private int m_count; internal WhenAllPromise(Task<T>[] tasks) :base()
{
Contract.Requires(tasks != null, "Expected a non-null task array");
Contract.Requires(tasks.Length > , "Expected a non-zero length task array");
m_tasks = tasks;
m_count = tasks.Length;
if (AsyncCausalityTracer.LoggingOn)
AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, this.Id, "Task.WhenAll", ); if (s_asyncDebuggingEnabled)
{
AddToActiveTasks(this);
}
foreach (var task in tasks)
{
if (task.IsCompleted) this.Invoke(task); // short-circuit the completion action, if possible
else task.AddCompletionAction(this); // simple completion action
}
} public void Invoke(Task ignored)
{
if (AsyncCausalityTracer.LoggingOn)
AsyncCausalityTracer.TraceOperationRelation(CausalityTraceLevel.Important, this.Id, CausalityRelation.Join); // Decrement the count, and only continue to complete the promise if we're the last one.
if (Interlocked.Decrement(ref m_count) == 0)
{
T[] results = new T[m_tasks.Length];
List<ExceptionDispatchInfo> observedExceptions = null;
Task canceledTask = null; for (int i = ; i < m_tasks.Length; i++)
{
Task<T> task = m_tasks[i];
Contract.Assert(task != null, "Constituent task in WhenAll should never be null"); if (task.IsFaulted)
{
if (observedExceptions == null) observedExceptions = new List<ExceptionDispatchInfo>();
observedExceptions.AddRange(task.GetExceptionDispatchInfos());
}
else if (task.IsCanceled)
{
if (canceledTask == null) canceledTask = task; // use the first task that's canceled
}
else
{
Contract.Assert(task.Status == TaskStatus.RanToCompletion);
results[i] = task.GetResultCore(waitCompletionNotification: false); // avoid Result, which would triggering debug notification
}
if (task.IsWaitNotificationEnabled) this.SetNotificationForWaitCompletion(enabled: true);
else m_tasks[i] = null; // avoid holding onto tasks unnecessarily
} if (observedExceptions != null)
{
Contract.Assert(observedExceptions.Count > , "Expected at least one exception");
TrySetException(observedExceptions);
}
else if (canceledTask != null)
{
TrySetCanceled(canceledTask.CancellationToken, canceledTask.GetCancellationExceptionDispatchInfo());
}
else
{
if (AsyncCausalityTracer.LoggingOn)
AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, this.Id, AsyncCausalityStatus.Completed); if (Task.s_asyncDebuggingEnabled)
{
RemoveFromActiveTasks(this.Id);
}
TrySetResult(results);
}
}
Contract.Assert(m_count >= , "Count should never go below 0");
} internal override bool ShouldNotifyDebuggerOfWaitCompletion
{
get
{
return base.ShouldNotifyDebuggerOfWaitCompletion && Task.AnyTaskRequiresNotifyDebuggerOfWaitCompletion(m_tasks);
}
}
}
}
首先我们来看看Task的WhenAny的实现,非常简单调用TaskFactory.CommonCWAnyLogic方法,直接返回Task,而WaitAny【也调用TaskFactory.CommonCWAnyLogic】则需要等待这个Task完成。接下来我们来看看WhenAll的实现,WhenAll核心方法是InternalWhenAll,在InternalWhenAll里面返回了一个WhenAllPromise的Task,WhenAllPromise里面有一个计数器m_count,每当Task完成一个,就调用WhenAllPromise的Invoke方法,实现计数器m_count减1,当计数器m_count为0时表示所有的Task有已经完成。【在Task的WaitAll里面用的是SetOnCountdownMres,和这里的WhenAllPromise相似,都有一个计数器】。
那么我们现在来看看TaskFactory的ContinueWhenAny和ContinueWhenAll的实现
public class TaskFactory
{
public Task ContinueWhenAny<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Action<Task<TAntecedentResult>> continuationAction,
CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler)
{
if (continuationAction == null) throw new ArgumentNullException("continuationAction");
Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return TaskFactory<VoidTaskResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler, ref stackMark);
}
// Creates a continuation Task<TResult> ,that will be started upon the completion of a set of provided Tasks.
public Task<TResult> ContinueWhenAll<TAntecedentResult>(Task<TAntecedentResult>[] tasks, Func<Task<TAntecedentResult>[], TResult> continuationFunction,
CancellationToken cancellationToken)
{
if (continuationFunction == null) throw new ArgumentNullException("continuationFunction");
Contract.EndContractBlock(); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler, ref stackMark);
} internal static Task<TResult> ContinueWhenAnyImpl<TAntecedentResult>(Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>, TResult> continuationFunction, Action<Task<TAntecedentResult>> continuationAction,
TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler, ref StackCrawlMark stackMark)
{ TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions);
if (tasks == null) throw new ArgumentNullException("tasks");
if (tasks.Length == ) throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"), "tasks");
Contract.Requires((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null");
if (scheduler == null) throw new ArgumentNullException("scheduler");
Contract.EndContractBlock(); var starter = TaskFactory.CommonCWAnyLogic(tasks); // Bail early if cancellation has been requested.
if (cancellationToken.IsCancellationRequested
&& ((continuationOptions & TaskContinuationOptions.LazyCancellation) == )
)
{
return CreateCanceledTask(continuationOptions, cancellationToken);
} // returned continuation task, off of starter
if (continuationFunction != null)
{
return starter.ContinueWith<TResult>(
GenericDelegateCache<TAntecedentResult, TResult>.CWAnyFuncDelegate,
continuationFunction, scheduler, cancellationToken, continuationOptions, ref stackMark);
}
else
{
Contract.Assert(continuationAction != null);
return starter.ContinueWith<TResult>(
// Use a cached delegate
GenericDelegateCache<TAntecedentResult,TResult>.CWAnyActionDelegate,
continuationAction, scheduler, cancellationToken, continuationOptions, ref stackMark);
}
}
internal static Task<TResult> ContinueWhenAllImpl<TAntecedentResult>(Task<TAntecedentResult>[] tasks,
Func<Task<TAntecedentResult>[], TResult> continuationFunction, Action<Task<TAntecedentResult>[]> continuationAction,
TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler, ref StackCrawlMark stackMark)
{ TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions);
if (tasks == null) throw new ArgumentNullException("tasks"); Contract.Requires((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null");
if (scheduler == null) throw new ArgumentNullException("scheduler");
Contract.EndContractBlock(); Task<TAntecedentResult>[] tasksCopy = TaskFactory.CheckMultiContinuationTasksAndCopy<TAntecedentResult>(tasks); if (cancellationToken.IsCancellationRequested
&& ((continuationOptions & TaskContinuationOptions.LazyCancellation) == )
)
{
return CreateCanceledTask(continuationOptions, cancellationToken);
} var starter = TaskFactory.CommonCWAllLogic(tasksCopy);
if (continuationFunction != null)
{
return starter.ContinueWith<TResult>(
// use a cached delegate
GenericDelegateCache<TAntecedentResult, TResult>.CWAllFuncDelegate,
continuationFunction, scheduler, cancellationToken, continuationOptions, ref stackMark);
}
else
{
Contract.Assert(continuationAction != null); return starter.ContinueWith<TResult>(
// use a cached delegate
GenericDelegateCache<TAntecedentResult, TResult>.CWAllActionDelegate,
continuationAction, scheduler, cancellationToken, continuationOptions, ref stackMark);
}
}
internal static Task<Task<T>[]> CommonCWAllLogic<T>(Task<T>[] tasksCopy)
{
Contract.Requires(tasksCopy != null); // Create a promise task to be returned to the user
CompleteOnCountdownPromise<T> promise = new CompleteOnCountdownPromise<T>(tasksCopy); for (int i = ; i < tasksCopy.Length; i++)
{
if (tasksCopy[i].IsCompleted) promise.Invoke(tasksCopy[i]); // Short-circuit the completion action, if possible
else tasksCopy[i].AddCompletionAction(promise); // simple completion action
} return promise;
}
private sealed class CompleteOnCountdownPromise<T> : Task<Task<T>[]>, ITaskCompletionAction
{
private readonly Task<T>[] _tasks;
private int _count; internal CompleteOnCountdownPromise(Task<T>[] tasksCopy) : base()
{
Contract.Requires((tasksCopy != null) && (tasksCopy.Length > ), "Expected non-null task array with at least one element in it");
_tasks = tasksCopy;
_count = tasksCopy.Length; if (AsyncCausalityTracer.LoggingOn)
AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, this.Id, "TaskFactory.ContinueWhenAll<>", ); if (Task.s_asyncDebuggingEnabled)
{
AddToActiveTasks(this);
}
} public void Invoke(Task completingTask)
{
if (AsyncCausalityTracer.LoggingOn)
AsyncCausalityTracer.TraceOperationRelation(CausalityTraceLevel.Important, this.Id, CausalityRelation.Join); if (completingTask.IsWaitNotificationEnabled) this.SetNotificationForWaitCompletion(enabled: true);
if (Interlocked.Decrement(ref _count) == 0)
{
if (AsyncCausalityTracer.LoggingOn)
AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, this.Id, AsyncCausalityStatus.Completed); if (Task.s_asyncDebuggingEnabled)
{
RemoveFromActiveTasks(this.Id);
} TrySetResult(_tasks);
}
Contract.Assert(_count >= , "Count should never go below 0");
} internal override bool ShouldNotifyDebuggerOfWaitCompletion
{
get
{
return base.ShouldNotifyDebuggerOfWaitCompletion && Task.AnyTaskRequiresNotifyDebuggerOfWaitCompletion(_tasks);
}
}
} }
首先我们来看看TaskFactory的ContinueWhenAny方法,ContinueWhenAny方法主要调用的是ContinueWhenAnyImpl,在ContinueWhenAnyImpl里面主要调用的是TaskFactory.CommonCWAnyLogic(tasks)方法,这个方法方返回的是一个CompleteOnInvokePromise Task,在Task的WhenAny方法中直接返回这个CompleteOnInvokePromise task,而Task的WaitAny则需要等待这个CompleteOnInvokePromise task的完成;而TaskFactory的ContinueWhenAny则是返回这个CompleteOnInvokePromise task的ContinueWith方法。
接下来我们在看看TaskFactory的ContinueWhenAll方法,ContinueWhenAll方法主要调用的是ContinueWhenAllImpl方法,ContinueWhenAllImpl方法主要是调用TaskFactory.CommonCWAnyLogic(tasks)方法,TaskFactory.CommonCWAnyLogic(tasks)方法返回一个CompleteOnCountdownPromise<T> 的task,然后ContinueWhenAllImpl最后返回这个task的ContinueWith方法,这里的CompleteOnCountdownPromise和Task的WhenAllPromise相似,里面都有一个计数器来标记里面的task是否执行完毕。
C# Task WhenAny和WhenAll 以及TaskFactory 的ContinueWhenAny和ContinueWhenAll的实现的更多相关文章
- 《C#并发编程经典实例》学习笔记—2.5 等待任意一个任务完成 Task.WhenAny
问题 执行若干个任务,只需要对其中任意一个的完成进行响应.这主要用于:对一个操作进行多种独立的尝试,只要一个尝试完成,任务就算完成.例如,同时向多个 Web 服务询问股票价格,但是只关心第一个响应的. ...
- 【转】【C#】【Thread】【Task】多线程
多线程 多线程在4.0中被简化了很多,仅仅只需要用到System.Threading.Tasks.::.Task类,下面就来详细介绍下Task类的使用. 一.简单使用 开启一个线程,执行循环方法,返回 ...
- 第四节:Task的启动的四种方式以及Task、TaskFactory的线程等待和线程延续的解决方案
一. 背景 揭秘: 在前面的章节介绍过,Task出现之前,微软的多线程处理方式有:Thread→ThreadPool→委托的异步调用,虽然也可以基本业务需要的多线程场景,但它们在多个线程的等待处理方面 ...
- C# Task TaskFactory 异步线程/异步任务
Task是.NetFramework3.0出现的,线程是基于线程池,然后提供了丰富的API TaskFactory 提供对创建和计划 Task 对象的支持 创建和启动异步任务 1.Task task ...
- c# Task waitAll,WhenAll
wait 阻塞的 when是异步的非阻塞的. Task[] tlist = new Task[] { Task.Run(() => { Thread.Sleep(3000); }), Task. ...
- 实践基于Task的异步模式
Await 返回该系列目录<基于Task的异步模式--全面介绍> 在API级别,实现没有阻塞的等待的方法是提供callback(回调函数).对于Tasks来说,这是通过像ContinueW ...
- 任务(task)
任务概述 线程(Thread)是创建并发的底层工具,因此有一定的局限性(不易得到返回值(必须通过创建共享域):异常的捕获和处理也麻烦:同时线程执行完毕后无法再次开启该线程),这些局限性会降低性能同时影 ...
- Class:Task 类
ylbtech-.Net-Class:Task 类 1. Task 类返回顶部 1-1. #region 程序集 mscorlib, Version=4.0.0.0, Culture=neutral, ...
- 多线程三:Task
Task是.NET 3.0中推出的,是基于ThreadPool封装的,里面的线程都是来自于ThreadPool. 1.使用Run()方法启动线程 F12查看Run()方法的定义: 发现Run()方法的 ...
随机推荐
- tomcat优化,java查看
java堆空间分为 新生代 ,老年代 , 持久代 各自有各自的垃圾回收算法 eden区:新生的对象存放在这经常被回收 from .to 存活区 在老年代,回收的频率不是很高 jdk8 就没有持久 ...
- ghithub中PHPOffice/PHPWord的学习
1.概念:PHPWord是用纯PHP提供了一组类写入和从不同的文档格式的文件阅读库.PHPWord的当前版本支持微软的Office Open XML(OOXML或处理OpenXML),用于Office ...
- 删除Docker中所有已停止的容器
方法一: #显示所有的容器,过滤出Exited状态的容器,取出这些容器的ID, sudo docker ps -a|grep Exited|awk '{print $1}' #查询所有的容器,过滤出E ...
- fastadmin系统配置
常规管理--->系统配置--->字典配置-->配置分组-->追加--填上键值-->回车 然后在点上图的+添加自定义的配置项(如果需要删除配置项,需要删除数据库中fa_co ...
- Python之IO编程——文件读写、StringIO/BytesIO、操作文件和目录、序列化
IO编程 IO在计算机中指Input/Output,也就是输入和输出.由于程序和运行时数据是在内存中驻留,由CPU这个超快的计算核心来执行,涉及到数据交换的地方,通常是磁盘.网络等,就需要IO接口.从 ...
- Philosopher’s Walk(递归)
In Programming Land, there are several pathways called Philosopher’s Walks for philosophers to have ...
- Django之模板基础
Django之模板 目录 变量 过滤器 标签的使用 变量 变量的引用格式 使用双括号,两边空格不能省略. 语法格式: {{var_name}} Template和Context对象 context 字 ...
- python之psutil模块(获取系统性能信息(CPU,内存,磁盘,网络)
一.psutil模块 1. psutil是一个跨平台库(http://code.google.com/p/psutil/),能够轻松实现获取系统运行的进程和系统利用率(包括CPU.内存.磁盘.网络等) ...
- Linux发展历史
一.硬件与软件发展历史 计算机由硬件和软件组成结构 硬件 1946年诞生于宾夕法尼亚州,占地170平米,重量达到30吨,名字叫做ENIAC(electronic numerical integrato ...
- ASP.NET MVC 常用路由总结
1.URL模式 路由系统用一组路由来实现它的功能,这些路由共同组成了应用系统URL架构或方案,这种URL架构是应用程序能够识别并能对之做出响应的一组URL,当处理一个输入 请求时,路由系统的工作是将这 ...