C # Task Source code reading (1)

Source: Internet
Author: User

Usually we develop, often use task, the subsequent versions of. NET are related to task, for example, Asyn,await has a task and we seldom pay attention to thread. Task has brought us a lot of convenience. Is that we pay less attention to the course of execution and more to the logic. But sometimes, there are some applications. You also have to consider the health of the task, such as whether it succeeds or fails. Often when people say that the task is executed by the thread pool, let's take a look at what the task is doing today and what he does when he executes it.

You can see the source code of the task from here, or you can download it directly from reference code.

Let's look at this code first.

 Public classTask:ithreadpoolworkitem, IAsyncResult, IDisposable {[threadstatic]Internal StaticTask T_currenttask;//The currently executing task.[ThreadStatic]Private StaticStackguard T_stackguard;//The stack Guard object for this thread        Internal Static intS_taskidcounter;//static counter used to generate unique task IDs        Private ReadOnly StaticTaskFactory s_factory =NewTaskFactory (); Private volatile intM_taskid;//This task's unique ID. Initialized only if it is ever requested        Internal ObjectM_action;//The body of the task.  might be action<object>, action<tstate> or Action.        Or possibly a Func. //If m_action is set to null it would indicate that we operate in the//"Externally triggered completion" mode, which is exclusively meant//For the signalling Task<tresult> (aka. Promise). In this mode,//we don ' t call Innerinvoke () in response to a wait (), but the simply wait on//The completion event which is set when the future class calls Finish (). //But the event would now being signalled if Cancel () is called}

First look at the interface inherited by the task class, Ithreadpoolitem this is related to the thread pool, IAsyncResult this and asynchronous execution of the back-off, here I'm not too much to say this,

Then we see that there is a field t_currenttask, and it is static, pointing to its own task. We do not know whether there is doubt, why this design, in fact, such a design in. NET many places, such as HttpContext and so on, the characteristics of the basic will have a current. It's kind of like a singleton, but it's starting to start well, and there's a little bit more that you can replace at any time and inject your own definition into something. It is perfectly OK to use him as a single case. Note that the access modifier here is internal static.

Then t_stackguard,s_taskidcounter as the name implies not too much introduction.

Here is S_factory Note that he is static and access modifiers, of course, if I use Factory mode, it is seldom to put the current factory inside the class to use. Someday I'm going to have to do this for the finished product I'm producing.

Then a more important field, m_action, executes the body. Do you remember how the so-called function was executed in the assembly, push a push B call xxxx. A, B is the parameter, XXXX executes the code for the jump address, and the transfer of parameters is usually passed through the stack. The net is placed directly into object, and the annotations are written clearly to those entrusted. But for a function, his execution is the address of call.

Then we look at the following fields

        Internal Object // A state object that can is optionally supplied, passed to action.        Internal //         internalreadonly//  A task ' s parent, or null if parent-less.        Internalvolatileint m_stateflags;

M_stateobject a guess also probably until the effect.

The following is a particularly important field m_taskscheduler, which is important in the execution process. Everyone usually Windows platform TaskScheduler may use more, speaking of TaskScheduler, function is reasonable time to arrange a reasonable task execution, is actually an executive manager. Of course, our development tools in SQL Server also have a similar job, job execution, we also want to choose the execution plan. Of course, the m_taskscheduler here may have its own meaning, is the Task Scheduler. Of course the task default TaskScheduler is a little bit different from the tool we just mentioned. Of course, everyone has an impression that it is used to dispatch a task. As for how to dispatch, each has its own plan.

m_StateFlags the Status Flag field. The execution of a task, I certainly would like to be until his current state, start, end, so this is well understood. There are many states in the thread type itself.

Continue looking at the code

    Public voidStart () {Start (taskscheduler.current); } Public voidStart (TaskScheduler scheduler) {//Read The volatile m_stateflags field once and cache it for subsequent operations            intFlags =m_StateFlags; //need to check this before (m_action = = null) because completed tasks would//set m_action to null. We would want to know if this is the reason that m_action = = null.            if(Iscompletedmethod (Flags)) {Throw NewInvalidOperationException (Environment.getresourcestring ("task_start_taskcompleted")); }            if(Scheduler = =NULL)            {                Throw NewArgumentNullException ("Scheduler"); }            varOptions =Optionsmethod (Flags); if(Options & (TaskCreationOptions) internaltaskoptions.promisetask)! =0)            {                Throw NewInvalidOperationException (Environment.getresourcestring ("task_start_promise")); }            if(Options & (TaskCreationOptions) internaltaskoptions.continuationtask)! =0)            {                Throw NewInvalidOperationException (Environment.getresourcestring ("Task_start_continuationtask")); }            //Make sure this Task only gets started once. Or else throw an exception.            if(Interlocked.compareexchange (refM_taskscheduler, Scheduler,NULL) !=NULL)            {                Throw NewInvalidOperationException (Environment.getresourcestring ("task_start_alreadystarted")); } scheduleandstart (true); }

We usually use the Start method, he will default to a TaskScheduler, we continue to look at the following method, the last call is the Scheduleandstart method, regardless of the previous validation, we focus on the implementation process, to understand this, We must be clear taskscheduler.current

What is the class, what is his function, if we write taskscheduler ourselves, then what to write, what to accomplish.

We continue to find the TaskScheduler class from reference code. We'll focus on the current first, regardless of the method.

  Public StaticTaskScheduler Current {Get{TaskScheduler current=internalcurrent; returnThe current??Taskscheduler.default; }        } Internal StaticTaskScheduler internalcurrent {Get{Task Currenttask=task.internalcurrent; return((Currenttask! =NULL)                     && ((currenttask.creationoptions & taskcreationoptions.hidescheduler) = =0)                    ) ? Currenttask.executingtaskscheduler:NULL; }        }

By default I continue to find the default property
 Public Static TaskScheduler Default         {            get            {                return  s_defaulttaskscheduler;            }        }    Private Static ReadOnly New Threadpooltaskscheduler ();

We step by step tracking, finally found the Threadpooltaskscheduler, then finally can task to link up the ThreadPool.

Look at the execution Scheduleandstart before we look at the
  if (Interlocked.compareexchange (ref m_taskscheduler, scheduler, NULL)! = NULL) The wording of this sentence, null judgment plus the assignment of the object. This can be borrowed from our usual code. 



C # Task Source code reading (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.