Multithreading (4) Task, multithreading task

Source: Internet
Author: User

Multithreading (4) Task, multithreading task

 

It is easy to create a thread by using a thread pool. However, using a thread pool does not support thread cancellation, completion, failure notifications, and other interactive operations. To solve these problems ,. net 4.0 brings the TPL (Task Parallel Library) Task Parallel Library. The following is a summary of the use of tasks.

Create and run a task

Using a task in. net 4.0 to create a thread is very simple. There are two methods: the following code:

1 namespace ConsoleApplication19 2 {3 class Program 4 {5 static void Main (string [] args) 6 {7 // method 1 8 var task1 = new Task (() => 9 {10 Console. writeLine ("Create and start task! "); 11}); 12 task1.Start (); 13 14 // method 215 Task. factory. startNew () => 16 {17 Console. writeLine ("Task factory start new task! "); 18}); 19 20 Console. ReadKey (); 21} 22} 23}View Code

 

Output result:

Note that the task is also based on the thread pool, so the execution sequence of the two tasks is not fixed.

Cancel task

After creating a new task, we can cancel it at any time. The cancellation method is as follows:

 

 

1 namespace ConsoleApplication20 2 {3 class Program 4 {5 static void Main (string [] args) 6 {7 Console. writeLine ("Main thread starting... "); 8 9 var cts = new CancellationTokenSource (); 10 var task1 = Task. factory. startNew () => 11 {12 TaskAction (cts. token); 13}); 14 15 Thread. sleep (3000); 16 Console. writeLine (string. format ("current task status: {0}", task1.Status); 17 18 // cancel task 19 cts. cancel (); 20 Con Sole. WriteLine ("start cancel task! "); 21 for (int I = 0; I <5; I ++) 22 {23 Thread. sleep (500); 24 Console. writeLine (string. format ("current task status: {0}", task1.Status); 25} 26 27 Console. writeLine ("Main thread completed! "); 28 Console. readKey (); 29} 30 31 public static void TaskAction (CancellationToken token) 32 {33 Console. writeLine ("Sub thread starting... "); 34 35 while (true) 36 {37 Thread. sleep (1000); 38 if (token. isCancellationRequested) 39 {40 Console. writeLine ("Sub thread be canceled! "); 41 return; 42} 43 Console. WriteLine (" Sub thread is running! "); 44} 45} 46 47} 48}View Code

Output result:

Create a task set and output results

The following code:

1 namespace ConsoleApplication21 2 {3 class Program 4 {5 static void Main (string [] args) 6 {7 // create a Task set and output result 8 var tasks = new List <Task <string> (); 9 10 var task1 = Task. factory. startNew <string> () => 11 {12 Console. writeLine ("task1 running on thread id:" + Thread. currentThread. managedThreadId); 13 return "task1"; 14}); 15 tasks. add (task1); 16 17 var task2 = Task. factory. startNew <string> () => 18 {19 Console. writeLine ("task2 running on thread id:" + Thread. currentThread. managedThreadId); 20 return "task2"; 21}); 22 tasks. add (task2); 23 24 var task3 = Task. factory. startNew <string> () => 25 {26 Console. writeLine ("task3 running on thread id:" + Thread. currentThread. managedThreadId); 27 return "task3"; 28}); 29 tasks. add (task3); 30 31 // output result 32 foreach (var item in tasks) 33 {34 Console. writeLine (item. result); // call the Result method of a Task is equivalent to calling a Task. waitAll (tasks. toArray (); 35} 36 37 Console. readKey (); 38} 39} 40}

 

Output result:

Note the following two points:

1. Each task starts a new thread and the running sequence is not fixed.

2. The Task. Result is equivalent to calling the Wait method and waiting for the asynchronous Task to complete.

Serializing multiple tasks

The following code:

1 namespace ConsoleApplication22 2 {3 class Program 4 {5 static void Main (string [] args) 6 {7 // serializing multi-Task 8 var task1 = Task. factory. startNew () => 9 {10 Console. writeLine ("start task1... "); 11 Console. writeLine ("current thread id:" + Thread. currentThread. managedThreadId); 12}); 13 14 var task2 = task1.ContinueWith (item) => 15 {16 Console. writeLine ("start task2... "); 17 Console. writeLine ("current thread id:" + Thread. currentThread. managedThreadId); 18}); 19 20 var task3 = task2.ContinueWith (item) => 21 {22 Console. writeLine ("start task3... "); 23 Console. writeLine ("current thread id:" + Thread. currentThread. managedThreadId); 24}); 25 26 Console. readKey (); 27} 28} 29}

Output result:

Note: After multi-task serialization, it is equivalent to sequential execution, and it is possible to use the same thread, which can be seen from the thread id.

Multi-task waiting for execution to complete

The following code:

1 namespace ConsoleApplication23 2 {3 class Program 4 {5 static void Main (string [] args) 6 {7 // multi-Task waiting for execution to complete 8 var tasks = new List <Task <string> (); 9 10 var task1 = Task. factory. startNew <string> () => 11 {12 Console. writeLine ("task1"); 13 return "task1"; 14}); 15 tasks. add (task1); 16 17 var task2 = Task. factory. startNew <string> () => 18 {19 Console. writeLine ("task2"); 20 return "task2"; 21}); 22 tasks. add (task2); 23 24 var task3 = Task. factory. startNew <string> () => 25 {26 Console. writeLine ("task3"); 27 return "task3"; 28}); 29 tasks. add (task3); 30 31 // wait for all tasks to complete 32 tasks. waitAll (tasks. toArray (); 33 34 // equivalent to the following call 35 // foreach (var item in tasks) 36 // {37 // item. result38 //} 39 40 Console. readKey (); 41} 42} 43}

 

Output result:

Note that if a task has a returned value, you can use Task. Result to obtain the returned value and Wait for the Task to be executed. This is equivalent to calling the Task. Wait method.

Create a subtask

The following code:

1 namespace ConsoleApplication24 2 {3 class Program 4 {5 static void Main (string [] args) 6 {7 // create subtask 8 var parentTask = Task. factory. startNew () => 9 {10 Console. writeLine ("parent task! "); 11 var childTask = Task. Factory. StartNew () => 12 {13 Console. WriteLine (" child task! "); 14}, TaskCreationOptions. AttachedToParent); 15}); 16 17 Console. ReadKey (); 18} 19} 20}

 

Output result:

 

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.