.NET Task揭秘(一)
public static Task Run(Action action, CancellationToken cancellationToken)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return Task.InternalStartNew((Task) null, (Delegate) action, (object) null, cancellationToken, TaskScheduler.Default, TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
}
public Task StartNew(Action<object> action, object state, CancellationToken cancellationToken)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Task internalCurrent = Task.InternalCurrent;
return Task.InternalStartNew(internalCurrent, (Delegate) action, state, cancellationToken, this.GetDefaultScheduler(internalCurrent), this.m_defaultCreationOptions, InternalTaskOptions.None, ref stackMark);
}
private TaskScheduler GetDefaultScheduler(Task currTask)
{
if (this.m_defaultScheduler != null)
return this.m_defaultScheduler;
if (currTask != null && (currTask.CreationOptions & TaskCreationOptions.HideScheduler) == TaskCreationOptions.None)
return currTask.ExecutingTaskScheduler;
return TaskScheduler.Default;
}
public abstract class TaskScheduler
{
private static readonly ConditionalWeakTable<TaskScheduler, object> s_activeTaskSchedulers = new ConditionalWeakTable<TaskScheduler, object>();
private static readonly TaskScheduler s_defaultTaskScheduler = (TaskScheduler) new ThreadPoolTaskScheduler();
...
}
internal static Task InternalStartNew(Task creatingTask, Delegate action, object state, CancellationToken cancellationToken, TaskScheduler scheduler, TaskCreationOptions options, InternalTaskOptions internalOptions, ref StackCrawlMark stackMark)
{
if (scheduler == null)
throw new ArgumentNullException("scheduler");
Task task = new Task(action, state, creatingTask, cancellationToken, options, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler);
task.PossiblyCaptureContext(ref stackMark);
task.ScheduleAndStart(false);
return task;
}
internal Task(Delegate action, object state, Task parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler)
{
if (action == null)
throw new ArgumentNullException("action");
if ((creationOptions & TaskCreationOptions.AttachedToParent) != TaskCreationOptions.None || (internalOptions & InternalTaskOptions.SelfReplicating) != InternalTaskOptions.None)
this.m_parent = parent;
this.TaskConstructorCore((object) action, state, cancellationToken, creationOptions, internalOptions, scheduler);
}
internal void TaskConstructorCore(object action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler)
{
this.m_action = action;
this.m_stateObject = state;
this.m_taskScheduler = scheduler;
if ((creationOptions & ~(TaskCreationOptions.PreferFairness | TaskCreationOptions.LongRunning | TaskCreationOptions.AttachedToParent | TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler | TaskCreationOptions.RunContinuationsAsynchronously)) != TaskCreationOptions.None)
throw new ArgumentOutOfRangeException("creationOptions");
if ((creationOptions & TaskCreationOptions.LongRunning) != TaskCreationOptions.None && (internalOptions & InternalTaskOptions.SelfReplicating) != InternalTaskOptions.None)
throw new InvalidOperationException(Environment.GetResourceString("Task_ctor_LRandSR"));
int num = (int) (creationOptions | (TaskCreationOptions) internalOptions);
if (this.m_action == null || (internalOptions & InternalTaskOptions.ContinuationTask) != InternalTaskOptions.None)
num |= ;
this.m_stateFlags = num;
if (this.m_parent != null && (creationOptions & TaskCreationOptions.AttachedToParent) != TaskCreationOptions.None && (this.m_parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == TaskCreationOptions.None)
this.m_parent.AddNewChild();
if (!cancellationToken.CanBeCanceled)
return;
this.AssignCancellationToken(cancellationToken, (Task) null, (TaskContinuation) null);
}
internal static ExecutionContext Capture(ref StackCrawlMark stackMark, ExecutionContext.CaptureOptions options)
{
ExecutionContext.Reader executionContextReader = Thread.CurrentThread.GetExecutionContextReader();
if (executionContextReader.IsFlowSuppressed)
return (ExecutionContext) null;
SecurityContext securityContext = SecurityContext.Capture(executionContextReader, ref stackMark);
HostExecutionContext executionContext1 = HostExecutionContextManager.CaptureHostExecutionContext();
SynchronizationContext synchronizationContext = (SynchronizationContext) null;
LogicalCallContext logicalCallContext = (LogicalCallContext) null;
if (!executionContextReader.IsNull)
{
if ((options & ExecutionContext.CaptureOptions.IgnoreSyncCtx) == ExecutionContext.CaptureOptions.None)
synchronizationContext = executionContextReader.SynchronizationContext == null ? (SynchronizationContext) null : executionContextReader.SynchronizationContext.CreateCopy();
if (executionContextReader.LogicalCallContext.HasInfo)
logicalCallContext = executionContextReader.LogicalCallContext.Clone();
}
Dictionary<IAsyncLocal, object> dictionary = (Dictionary<IAsyncLocal, object>) null;
List<IAsyncLocal> asyncLocalList = (List<IAsyncLocal>) null;
if (!executionContextReader.IsNull)
{
dictionary = executionContextReader.DangerousGetRawExecutionContext()._localValues;
asyncLocalList = executionContextReader.DangerousGetRawExecutionContext()._localChangeNotifications;
}
if ((options & ExecutionContext.CaptureOptions.OptimizeDefaultCase) != ExecutionContext.CaptureOptions.None && securityContext == null && (executionContext1 == null && synchronizationContext == null) && ((logicalCallContext == null || !logicalCallContext.HasInfo) && (dictionary == null && asyncLocalList == null)))
return ExecutionContext.s_dummyDefaultEC;
ExecutionContext executionContext2 = new ExecutionContext();
executionContext2.SecurityContext = securityContext;
if (executionContext2.SecurityContext != null)
executionContext2.SecurityContext.ExecutionContext = executionContext2;
executionContext2._hostExecutionContext = executionContext1;
executionContext2._syncContext = synchronizationContext;
executionContext2.LogicalCallContext = logicalCallContext;
executionContext2._localValues = dictionary;
executionContext2._localChangeNotifications = asyncLocalList;
executionContext2.isNewCapture = true;
return executionContext2;
}
internal void ScheduleAndStart(bool needsProtection)
{
if (needsProtection)
{
if (!this.MarkStarted())
return;
}
else
this.m_stateFlags = this.m_stateFlags | ;
if (Task.s_asyncDebuggingEnabled)
Task.AddToActiveTasks(this);
if (AsyncCausalityTracer.LoggingOn && (this.Options & (TaskCreationOptions) ) == TaskCreationOptions.None)
AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, this.Id, "Task: " + ((Delegate) this.m_action).Method.Name, 0UL);
try
{
this.m_taskScheduler.InternalQueueTask(this);
}
catch (ThreadAbortException ex)
{
this.AddException((object) ex);
this.FinishThreadAbortedTask(true, false);
}
catch (System.Exception ex)
{
TaskSchedulerException schedulerException = new TaskSchedulerException(ex);
this.AddException((object) schedulerException);
this.Finish(false);
if ((this.Options & (TaskCreationOptions) ) == TaskCreationOptions.None)
this.m_contingentProperties.m_exceptionsHolder.MarkAsHandled(false);
throw schedulerException;
}
} internal void InternalQueueTask(Task task)
{
task.FireTaskScheduledIfNeeded(this);
this.QueueTask(task);
}
private static readonly ParameterizedThreadStart s_longRunningThreadWork = new ParameterizedThreadStart(ThreadPoolTaskScheduler.LongRunningThreadWork);
private static void LongRunningThreadWork(object obj)
{
(obj as Task).ExecuteEntry(false);
}
protected internal override void QueueTask(Task task)
{
if ((task.Options & TaskCreationOptions.LongRunning) != TaskCreationOptions.None)
{
new Thread(ThreadPoolTaskScheduler.s_longRunningThreadWork)
{
IsBackground = true
}.Start((object) task);
}
else
{
bool forceGlobal = (uint) (task.Options & TaskCreationOptions.PreferFairness) > 0U;
ThreadPool.UnsafeQueueCustomWorkItem((IThreadPoolWorkItem) task, forceGlobal);
}
}
public void Enqueue(IThreadPoolWorkItem callback, bool forceGlobal)
{
ThreadPoolWorkQueueThreadLocals queueThreadLocals = (ThreadPoolWorkQueueThreadLocals) null;
if (!forceGlobal)
queueThreadLocals = ThreadPoolWorkQueueThreadLocals.threadLocals;
if (this.loggingEnabled)
FrameworkEventSource.Log.ThreadPoolEnqueueWorkObject((object) callback);
if (queueThreadLocals != null)
{
queueThreadLocals.workStealingQueue.LocalPush(callback);
}
else
{
ThreadPoolWorkQueue.QueueSegment comparand = this.queueHead;
while (!comparand.TryEnqueue(callback))
{
Interlocked.CompareExchange<ThreadPoolWorkQueue.QueueSegment>(ref comparand.Next, new ThreadPoolWorkQueue.QueueSegment(), (ThreadPoolWorkQueue.QueueSegment) null);
for (; comparand.Next != null; comparand = this.queueHead)
Interlocked.CompareExchange<ThreadPoolWorkQueue.QueueSegment>(ref this.queueHead, comparand.Next, comparand);
}
}
this.EnsureThreadRequested();
}
internal volatile IThreadPoolWorkItem[] m_array = new IThreadPoolWorkItem[];
private SpinLock m_foreignLock = new SpinLock(false);
public void LocalPush(IThreadPoolWorkItem obj)
{
int num1 = this.m_tailIndex;
if (num1 == int.MaxValue)
{
bool lockTaken = false;
try
{
this.m_foreignLock.Enter(ref lockTaken);
if (this.m_tailIndex == int.MaxValue)
{
this.m_headIndex = this.m_headIndex & this.m_mask;
this.m_tailIndex = num1 = this.m_tailIndex & this.m_mask;
}
}
finally
{
if (lockTaken)
this.m_foreignLock.Exit(true);
}
}
if (num1 < this.m_headIndex + this.m_mask)
{
Volatile.Write<IThreadPoolWorkItem>(ref this.m_array[num1 & this.m_mask], obj);
this.m_tailIndex = num1 + ;
}
else
{
bool lockTaken = false;
try
{
this.m_foreignLock.Enter(ref lockTaken);
int num2 = this.m_headIndex;
int num3 = this.m_tailIndex - this.m_headIndex;
if (num3 >= this.m_mask)
{
IThreadPoolWorkItem[] threadPoolWorkItemArray = new IThreadPoolWorkItem[this.m_array.Length << ];
for (int index = ; index < this.m_array.Length; ++index)
threadPoolWorkItemArray[index] = this.m_array[index + num2 & this.m_mask];
this.m_array = threadPoolWorkItemArray;
this.m_headIndex = ;
this.m_tailIndex = num1 = num3;
this.m_mask = this.m_mask << | ;
}
Volatile.Write<IThreadPoolWorkItem>(ref this.m_array[num1 & this.m_mask], obj);
this.m_tailIndex = num1 + ;
}
finally
{
if (lockTaken)
this.m_foreignLock.Exit(false);
}
}
}
.NET Task揭秘(一)的更多相关文章
- 学习ASP.NET Web API框架揭秘之“HTTP方法重写”
最近在看老A的<ASP.NET Web API 框架揭秘>,这本书对于本人现阶段来说还是比较合适的(对于调用已经较为熟悉,用其开发过项目,但未深入理解过很多内容为何可以这样“调用”).看到 ...
- Spark Tungsten揭秘 Day3 内存分配和管理内幕
Spark Tungsten揭秘 Day3 内存分配和管理内幕 恭喜Spark2.0发布,今天会看一下2.0的源码. 今天会讲下Tungsten内存分配和管理的内幕.Tungsten想要工作,要有数据 ...
- Spark Streaming揭秘 Day30 集群模式下SparkStreaming日志分析
Spark Streaming揭秘 Day30 集群模式下SparkStreaming日志分析 今天通过集群运行模式观察.研究和透彻的刨析SparkStreaming的日志和web监控台. Day28 ...
- Spark Streaming揭秘 Day17 资源动态分配
Spark Streaming揭秘 Day17 资源动态分配 今天,让我们研究一下一个在Spark中非常重要的特性:资源动态分配. 为什么要动态分配?于Spark不断运行,对资源也有不小的消耗,在默认 ...
- Spark Streaming揭秘 Day4-事务一致性(Exactly one)
Spark Streaming揭秘 Day4 事务一致性Exactly one 引子 对于业务处理系统,事务的一致性非常的关键,事务一致性(Exactly one),简单来说,就是输入数据一定会被处理 ...
- ASP.NET Web API框架揭秘:路由系统的几个核心类型
ASP.NET Web API框架揭秘:路由系统的几个核心类型 虽然ASP.NET Web API框架采用与ASP.NET MVC框架类似的管道式设计,但是ASP.NET Web API管道的核心部分 ...
- 第四节:Task的启动的四种方式以及Task、TaskFactory的线程等待和线程延续的解决方案
一. 背景 揭秘: 在前面的章节介绍过,Task出现之前,微软的多线程处理方式有:Thread→ThreadPool→委托的异步调用,虽然也可以基本业务需要的多线程场景,但它们在多个线程的等待处理方面 ...
- 第五节:Task构造函数之TaskCreationOptions枚举处理父子线程之间的关系。
一. 整体说明 揭秘: 通过F12查看Task类的源码(详见下面的截图),发现Task类的构造函数有有一个参数为:TaskCreationOptions类型,本章节可以算作是一个扩展章节,主要就来研究 ...
- 第六节:深入研究Task实例方法ContinueWith的参数TaskContinuationOptions
一. 整体说明 揭秘: 该章节的性质和上一个章节类似,也是一个扩展的章节,主要来研究Task类下的实例方法ContinueWith中的参数TaskContinuationOptions. 通过F12查 ...
随机推荐
- (DNS被劫持所导致的)QQ音乐与视频网页打开很慢的解决方法
这周开始发现一个很让人抓狂的现象,QQ音乐网页(http://y.qq.com)与QQ视频(http://v.qq.com/)网页打开超慢,甚至是无法打开,严重影响了业余的音乐视频生活. 以QQ视频为 ...
- A*寻路算法
对于初学者而言,A*寻路已经是个比较复杂的算法了,为了便于理解,本文降低了A*算法的难度,规定只能横竖(四方向)寻路,而无法直接走对角线,使得整个算法更好理解. 简而言之,A*寻路就是计算从起点经过该 ...
- 如何调试ANDROID下面黑屏问题
最近很多朋友在问,为毛在WINDOWS下对了,跑ANDROID的虚拟机或者真机就黑屏了, 有的是只有FPS信息,有的是连FPS信息都没有.如果是程序能够正常启动,不会闪退,但显示不对. 那十有八九都是 ...
- 《3D Math Primer for Graphics and Game Development》读书笔记2
<3D Math Primer for Graphics and Game Development>读书笔记2 上一篇得到了"矩阵等价于变换后的基向量"这一结论. 本篇 ...
- js动态生成选项之考试系统(一)
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"% ...
- My first makefile to compile multiple C files
I have three files to compile: main.c, func.c, func.h The steps: 1 main.c to main.o 2 func. ...
- SqlServer2008到期升级企业版 密钥+图解
最近使用SQL Server2008,结果Sql Server Management Studio提示过期了,如图: 遇到如上图情况,需要将SQL Server2008升级维护下,还是输入原来的密钥就 ...
- ajax局部刷新后,如何让局部中的百度分享重新加载
我这个人不怎么喜欢说太多话,看几个图你们就懂了 Ajax前 Ajax之后 原因分析 解决方法 收工 百度分享是集成了众多主流第三方网站分享和收藏按钮的工具. 通过百度分享轻松将主流第三方网站的分享按钮 ...
- 【已解决】WinPhone模拟器报错:模拟器没法确定来宾虚拟机通信的主机ID地址。某些功能已被禁用
先看警告 再看错误信息 计算机管理打不开就==>Win+R ==>compmgmt.msc 发现,dnt在管理员权限组里面,也在Hyper-V权限组里面 看看Hyper-V的驱动有木有被禁 ...
- c#写windows服务
序言 前段时间做一个数据迁移项目,刚开始用B/S架构做的项目,但B/S要寄存在IIs中,而IIs又不稳定因素,如果重启IIs就要打开页面才能运行项目.有不便之处,就改用Windows服务实现.这篇就总 ...