5 days to go to C # Parallel and multithreaded Programming series articles Directory
5 days of playing C # parallel and multithreaded programming--the first day to meet parallel
5 days of playing C # parallel and multithreaded programming--next day parallel collections and PLINQ
5 days to play C # parallel and multithreaded programming--third day recognize and use task
5 days to play C # parallel and multithreaded programming--fourth day task advanced
5 days of playing C # parallel and multithreaded programming--the fifth day multithreading programming big summary
For multi-threading, we often use thread. Before we know the task, if we are going to use multi-core functionality we might be able to thread ourselves, but this threading model is impacted by a "task-based programming model" after. NET 4.0, because the task will have a much smaller performance overhead than thread, but there are certainly doubts What is the difference between a task and a thread?
The difference between a task and a thread:
1, the task is the framework on the thread above, that is, the task will eventually be thrown to the threads to execute.
2, the task and the thread is not a one-to-one relationship, such as open 10 task does not mean to open 10 threads, this task is a bit like a thread pool, but the task compared to the thread pool has little overhead and precise control.
I. Understanding the basic use of task and task
1. Recognize task
First, consider the inheritance structure of the task. The task identifies an asynchronous operation.
You can see that the task and thread are located under the System.Threading namespace, which means they have a direct and inseparable connection. Let's take a closer look at it!
2. Create a task
There are two ways to create a task, one is to create the--new directly, and the other is to create it through a factory. Here's a look at the two ways to create:
The first way to create a direct instantiation of var task1 = new Task (() + = { //todo you code });
This is the simplest way to create, you can see its constructor is an action, its constructor has the following several, the more commonly used are the first two.
The second way to create the factory is to create var task2 = Task.Factory.StartNew (() + = { //todo you code });
This approach creates a task and runs through a static factory. Let's build a console project that demonstrates the following code:
The System.Threading.Tasks name control reference to add.
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Namespace taskdemo{ class program { static void Main (string[] args) { var task1 = new Task (() =>< c5/>{ Console.WriteLine ("Hello,task"); }); Task1. Start (); var task2 = Task.Factory.StartNew (() = { Console.WriteLine ("Hello,task started by Task Factory"); }); console.read ();}}}
Here I create two tasks in two different ways and let them run. You can see that the task created by the constructor has to start manually, and the task created by the factory is started directly.
Let's take a look at the declaration cycle of a task and write the following code:
var task1 = new Task (() = { Console.WriteLine ("Begin"); System.Threading.Thread.Sleep (+); Console.WriteLine ("Finish"); }); Console.WriteLine ("Before Start:" + Task1. Status); Task1. Start (); Console.WriteLine ("After start:" + Task1. Status); Task1. Wait (); Console.WriteLine ("After Finish:" + task1. Status); Console.read ();
Task1. Status is the current state of the output task, and its output is as follows:
You can see that the state before the call start is created, and then wait for the assigned thread to execute until the final execution is complete.
From the brief life cycle of the task we can derive:
Created: Represents the default initialization task, but the factory-created instance skips directly.
Waitingtorun: This status means waiting for the Task Scheduler to assign threads to the task execution.
Rantocompletion: Task execution is complete.
Ii. Task Control of tasks
The most appealing part of the task is his mission control, which allows you to control the order of task execution and allow multiple tasks to work in an orderly manner. Here's a detailed look at:
1, task.wait
In the last example, we have used, Task1. Wait (); we can see that the last Task1 state changes to completed when the task execution is completed.
2, Task.waitall
Look at the literal meaning, just wait for all the tasks to be done, let's write a code to demonstrate:
static void Main (string[] args) { var task1 = new Task (() = { Console.WriteLine ("Task 1 Begin"); System.Threading.Thread.Sleep (+); Console.WriteLine ("Task 1 Finish"); }); var task2 = new Task (() = { Console.WriteLine ("Task 2 Begin"); System.Threading.Thread.Sleep (+); Console.WriteLine ("Task 2 Finish"); }); Task1. Start (); Task2. Start (); Task.waitall (Task1, task2); Console.WriteLine ("All Task finished!"); Console.read (); }
The output results are as follows:
As you can see, task one and task two are finished before you output all task finished!
3, Task.waitany
This with the Task.waitall, is to wait for any task to complete the execution continues down, the above code WaitAll replaced with WaitAny, the output is as follows:
4, Task.continuewith
is to automatically start the next task after the first task completes, to implement the continuation of the task, let's look at his usage, and write the following code:
static void Main (string[] args) { var task1 = new Task (() = { Console.WriteLine ("Task 1 Begin"); System.Threading.Thread.Sleep (+); Console.WriteLine ("Task 1 Finish"); }); var task2 = new Task (() = { Console.WriteLine ("Task 2 Begin"); System.Threading.Thread.Sleep (+); Console.WriteLine ("Task 2 Finish"); }); Task1. Start (); Task2. Start (); var result = Task1. continuewith<string> (task = { Console.WriteLine ("Task1 finished!"); Return "This is Task result!"; }); Console.WriteLine (Result. Result.tostring ()); Console.read (); }
The results of the implementation are as follows:
As you can see, after the Task1 is finished, we begin to execute the following, and here we get the return value of the task.
Each time the ContinueWith method is called, a reference to the last task is passed in in order to detect the state of the last task, for example, we can use the result property of the last task to get the return value. We can also write this:
var sendfeedbacktask = Task.Factory.StartNew (() = {Console.WriteLine ("Get some data!");}) . Continuewith<bool> (s = = {return true;}) . Continuewith<string> (r + = { if (R.result) { return "finished"; } else { return "Error"; } }); Console.WriteLine (Sendfeedbacktask.result);
First output get some data, then execute the second to get the return value true, and then return finished or error as judged. Output Result:
Get some data!
Finished
In fact, the above to simplify the wording, you can write:
Task.factory.startnew<string> (() = {return "one";}). ContinueWith (ss = {Console.WriteLine (ss. (Result);});
Output one, this can see the bar ~
For more continuewith usage See also: http://technet.microsoft.com/zh-CN/library/dd321405
5. Cancellation of Task
In front of the usage of so many tasks, we can cancel this task if we start a task, an exception or a user click Cancel, and so on.
How to cancel a task, we cancel a task by cancellation's tokens. In the body of many tasks contains loops, we can determine whether the IsCancellationRequested property is true at polling time, if true, return or throw an exception, throw an exception, because there is nothing to say about exception handling.
Below in the code see how to implement the cancellation of the task, the code is as follows:
var tokensource = new CancellationTokenSource (); var token = Tokensource.token; var task = Task.Factory.StartNew (() = {for (var i = 0; i <; i++) { System.Threading.Thread.Sl EEP (+); if (token. iscancellationrequested) { Console.WriteLine ("Abort Mission success!"); return;}} }, token); Token. Register (() = { Console.WriteLine ("Canceled"); }); Console.WriteLine ("Press ENTER to cancel task ..."); Console.readkey (); Tokensource.cancel ();
Console.readkey ();//This sentence forgot to add, the program quit, see "Abort Mission success!" This tip
Here a task is opened, and token is registered with a method, output a message, and then execute Readkey start waiting for the user input, the user clicks Enter, executes the Tokensource.cancel method, cancels the task. The output results are as follows:
5 days to play C # parallel and multithreaded programming--third day recognize and use task