Parallel Programming-task Base

Source: Internet
Author: User

Parallel.for/foreach is a data-plane parallelism, the task in this paper is to carry out different operations in parallel, the main content of this article:

    1. Working model of Task
    2. Initializing a task
    3. Complete task
    4. Cancel Task
I. Task work model

. The working mode of task in net is Fork/join or Master/worker mode. The core idea is that Master is responsible for accepting the client's request and is responsible for assigning the request to the final wroker,worker after performing his or her work and returning it to master respectively. The final result is summarized by master and returned to the client.

In. NET task parallel programming. A worker represents a task.

second, initialize the task2.1 Parallel.Invoke

Parallel.Invoke is the simplest method of task parallel programming mode.

2.2 taskfactory.startnew

The method creates a task that is used to execute the method as a parameter.

    classTaskdemo { Public voidAction1 () {Console.WriteLine ("In action1"); }         Public voidAction2 () {Console.WriteLine ("In Action2"); }         Public voidstarttasks () {varTask1 = Task.Factory.StartNew(Action1); varTask2 = Task.Factory.StartNew(Action2); Task. WaitAll        (Task1, Task2); }    }

The code above uses the Taskfactory.startnew method to create two tasks. Task1 is used to perform action1,task2 for performing Action2.

StartNew just creates a task and joins the task into a work queue, when the task is not executed immediately and when the task is executed is determined by TaskScheduler. TaskScheduler will take out the task that needs to be executed before it starts executing. (The code above uses the default TaskScheduler)

TaskScheduler is likely to be executed at once, or at a specific point in the future, depending on the scheduling algorithm and CPU resources.

Iii. Completion of the task

I was just beginning to say. Task programming uses the Master/worker pattern, the last point in which the worker eventually returns the result to master. The results are aggregated by master unification. There are two methods in task programming:

    1. Task.waitall. Wait for all the task (worker) to complete.
    2. Task.waitany, wait for any task to complete.
3.1 Task.waitall

The above 2.2 code already uses WaitAll, the method will wait for two action to complete before return, the above method to do a little change.

classTaskdemo { Public voidAction1 () {Thread.Sleep ( +); Console.WriteLine ("In action1"); }         Public voidAction2 () {Thread.Sleep ( the); Console.WriteLine ("In Action2"); }         Public voidstarttasks () {varTask1 =Task.Factory.StartNew (Action1); varTask2 =Task.Factory.StartNew (Action2);            Task.waitall (Task1, Task2); Console.WriteLine ("finished"); }    }

WaitAll then print out "finished", according to WaitAll definition, finished is always the last printed string.

3.2 Task.waitany

Modify the WaitAll of the above code to WaitAny

        Public void starttasks ()        {            var task1 = Task.Factory.StartNew (Action1);             var task2 = Task.Factory.StartNew (Action2);            Task. WaitAny (Task1, task2);            Console.WriteLine ("finished");        }

Final Run Result:

It can be seen that after the use of WaitAny, did not wait for Task2 execution, the program went back to the main thread, first printed out the finished.

Iv. cancellation of Task4.1 Cancellation Process

The task cancels a task cancellation using a model called coorperative cancellation. Mainly use CancellationTokenSource to complete. The object has a cancellactiontoken. When startnew a task, the Toker can be passed to the created task. When CancellationTokenSource calls Cancel, the token state of the task will become canceled (Canceled) and the state of the task will become canceled. At this point, if the task is not started, the task will no longer perform the tasks.

Of course, the token is also judged within each task, and if token has been canceled, the current action is no longer executed (some tasks may have been started before Cancellactiontoke is canceled), and the execution diagram will be modified:

4.2 Demo Code
   classTaskdemo { Public voidAction1 (CancellationTokenSource cts) {if(CTS. iscancellationrequested) {return; } Console.WriteLine ("In action1"); }         Public voidAction2 (CancellationTokenSource cts) {Thread.Sleep ( -); if(CTS. iscancellationrequested) {Console.WriteLine ("Action2 is canceled"); return; } Console.WriteLine ("In Action2"); }         Public voidstarttasks () {CancellationTokenSource cts=NewCancellationTokenSource (); varTask1 = Task.Factory.StartNew (() =Action1 (CTS), CTS.            Token); varTask2 = Task.Factory.StartNew (() =Action2 (CTS), CTS.            Token);            Task.waitany (Task1, Task2); Cts.            Cancel (); Console.WriteLine ("finished"); }    }
4.3 running results

The result of the above operation may be "Action2 is canceled" This sentence will not print out, because it is possible to Task2 before the execution of the CTS has been canceled. Will enter the first if judgment point in the flowchart = = "Not would run task

Parallel Programming-task Base

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.