. Net 4.0 Parallel programming (5) Task (medium)

Source: Internet
Author: User

In the previous article, we saw how to create a Task. This article describes the use of various types of tasks.

Task Continuations
First, let's look at the continuation Task. The so-called continuation Task is to automatically start the next Task after the first Task is completed. We use the ContinueWith method to create a continuation Task. Let's assume that there is a service that accepts xml parsing. First, it accepts files from a certain place, then parses the files into the database, and finally returns whether the receipt is correctly parsed:

View sourceprint? 1 [TestMethod]

2 public void TaskParallelPrint ()

3 {

4 var paietask = new Task () => extends exml ());

5 var ResolveTask = paietask. ContinueWith <bool> (r) => ResolveXml ());

6 var SendFeedBackTask = ResolveTask. ContinueWith <string> (s) => SendFeedBack (s. Result ));

7 ReceiveTask. Start ();

8 Console. WriteLine (SendFeedBackTask. Result );

9}

Each time you call the ContinueWith method, the reference of the previous Task is passed in to check the status of the previous Task. For example, you can use the Result attribute of the previous Task to obtain the returned value. We can also write this statement for the purchase agent above:

View sourceprint? 1 [TestMethod]

2 public void TaskParallelPrint ()

3 {

4 var SendFeedBackTask = Task. Factory. StartNew () => limit exml ())

5. ContinueWith <bool> (s => ResolveXml ())

6. ContinueWith <string> (r => SendFeedBack (r. Result ));

7 Console. WriteLine (SendFeedBackTask. Result );

8}

Detached Nested Tasks
In some cases, we need to create nested tasks, which are divided into separated tasks and non-separated tasks. The creation method is simple, that is, to create a new Task in the Task body. If the AttachedToParent option is not specified for the new Task, the nested Task is separated. Let's look at the following code:

01 var outTask = Task. Factory. StartNew () =>

02 {

03 Console. WriteLine ("Outer task beginning ...");

04 var childTask = Task. Factory. StartNew () =>

05 {

06 Thread. SpinWait (3000000 );

07 Console. WriteLine ("Detached nested task completed .");

08 });

09 });

10 outTask. Wait ();

11 Console. WriteLine ("Outer task completed .");

12 Console. ReadKey ();

The running result is as follows:

OutTask. Wait () in the code above indicates that the outTask is waiting for completion.

Child Tasks
Add the TaskCreationOptions option to the above Code:

01 var outTask = Task. Factory. StartNew () =>

02 {

03 Console. WriteLine ("Outer task beginning ...");

04 var childTask = Task. Factory. StartNew () =>

05 {

06 Thread. SpinWait (3000000 );

07 Console. WriteLine ("Detached nested task completed .");

08}, TaskCreationOptions. AttachedToParent );

09 });

10 outTask. Wait ();

11 Console. WriteLine ("Outer task completed .");

12 Console. ReadKey ();

See the running result:

Cancellation Task
How to cancel a Task? We use the tokens of cancellation to cancel a Task. The Body of many tasks contains loops. When polling, we can determine whether the IsCancellationRequested attribute is True. If it is True, we can stop the loop and release resources, at the same time, an OperationCanceledException exception is thrown. Let's take a look at the sample code:

01 var tokenSource = new CancellationTokenSource ();

02 var token = tokenSource. Token;

03 var task = Task. Factory. StartNew () =>

04 {

05 for (var I = 0; I <10000000; I ++)

06 {

07 if (token. IsCancellationRequested)

08 {

09 Console. WriteLine ("Task cacel started ...");

10 throw new OperationCanceledException (token );

11}

12

13}

14}, token );

15 token. Register () =>

16 {

17 Console. WriteLine ("Canceled ");

18 });

19 Console. WriteLine ("Press enter again to cancel task ");

20 Console. ReadKey ();

21 tokenSource. Cancel ();

22 try

23 {

24 task. Wait ();

25}

26 catch (aggresponexception e)

27 {

28 foreach (var v in e. InnerExceptions)

29 Console. WriteLine ("msg:" + v. Message );

30

31}

32 Console. ReadKey ();

Summary
This article describes how to create different tasks and how to cancel tasks. In the next article, we will describe Exception Handling and Task Laizy.

 

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.