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:
// First creation method, direct instantiation var 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.
// second way to create, factory 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.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacetaskdemo{classProgram {Static voidMain (string[] args) { varTask1 =NewTask (() ={Console.WriteLine ("Hello,task"); }); Task1. Start (); varTask2 = 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:
varTask1 =NewTask (() ={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 voidMain (string[] args) { varTask1 =NewTask (() ={Console.WriteLine ("Task 1 Begin"); System.Threading.Thread.Sleep ( -); Console.WriteLine ("Task 1 Finish"); }); varTask2 =NewTask (() ={Console.WriteLine ("Task 2 Begin"); System.Threading.Thread.Sleep ( the); 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 voidMain (string[] args) { varTask1 =NewTask (() ={Console.WriteLine ("Task 1 Begin"); System.Threading.Thread.Sleep ( -); Console.WriteLine ("Task 1 Finish"); }); varTask2 =NewTask (() ={Console.WriteLine ("Task 2 Begin"); System.Threading.Thread.Sleep ( the); Console.WriteLine ("Task 2 Finish"); }); Task1. Start (); Task2. Start (); varresult = 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:
varSendfeedbacktask = 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:
varTokensource =NewCancellationTokenSource (); vartoken =Tokensource.token; varTask = Task.Factory.StartNew (() = { for(vari =0; I < +; i++) {System.Threading.Thread.Sleep ( +); 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 ();
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:
All right, let's talk about this here today, and go on with the task tomorrow, and then we'll talk about the exception handling of the task and some other usage, and if you like to follow me, I'll let you have an update.
Cloud drizzling
Blog Address: http://www.cnblogs.com/yunfeifei/
Disclaimer: The original text of this blog only represents my work in a certain time to summarize the views or conclusions, and my unit does not have a direct interest in the relationship. Non-commercial, unauthorized, post please keep the status quo, reprint must retain this paragraph statement, and in the article page obvious location to the original connection.
5 days to play C # parallel and multithreaded programming--third day recognize and use task