In previous articles, we have introduced Parallel Loop (upper, middle, and lower. This article will introduce the basic part of the Task.
First knowledge of Task
First, let's build a Demo of a simple Task:
View sourceprint? 1 static void Main (string [] args)
2 {
3 Task. Factory. StartNew () =>
4 {
5 Console. WriteLine ("Hello word! ");
6 });
7 Console. Read ();
8}
In the above Code, we have constructed a simple code using the Task class and created a Task through its Factory attribute. The running results can be imagined. In fact, the above Code is as follows:
View sourceprint? 1 static void Main (string [] args)
2 {
3 Task task = new Task () =>
4 {
5 Console. WriteLine ("Hello, Word! ");
6 });
7 task. Start ();
8 Console. Read ();
9}
The same is true, but the StartNew method directly constructs a Task and calls its Start method. The content executed within a Task is called the Body of the Task. The Task provides multiple methods for initializing and overloading. Let's look at the following example:
View sourceprint? 01 static void Main (string [] args)
02 {
03 Task 1 = new Task () =>
04 {
05 Console. WriteLine ("Message: Say" Hello "from task1 ");
06 });
07 Task 2 = new Task (new Action <object> (printMessage ),
08 "Say" Hello "from task2 ");
09
10 Task task3 = new Task (obj) =>{ printMessage (obj );},
11 "Say" Hello "from task3 ");
12
13 Task 4 = new Task (obj) => {Console. WriteLine ("Message: {0}", obj );},
14 "Say" Hello "from task4 ");
15
16 task1.Start ();
17 task2.Start ();
18 task3.Start ();
19 task4.Start ();
20 Console. Read ();
21}
In the preceding example, the State parameter of the overload method is used. The running result is as follows:
It seems that the result is not the same as what we think. In fact, we can understand it after careful consideration.
Return Value
View sourceprint? 01 static void Main (string [] args)
02 {
03 var loop = 0;
04 var task1 = new Task <int> () =>
05 {
06 for (var I = 0; I <1000; I ++)
07 loop + = I;
08 return loop;
09 });
10 task1.Start ();
11 var loopResut = task1.Result;
12 var task2 = new Task <long> (obj =>
13 {
14 long res = 0;
15 var looptimes = (int) obj;
16 for (var I = 0; I <looptimes; I ++)
17 res + = I;
18 return res;
19}, loopResut );
20
21 task2.Start ();
22 var resultTask2 = task2.Result;
23
24 Console. WriteLine ("Task1s result: {0} Task2s result: {1 }",
25 loopResut,
26 resultTask2 );
27 Console. ReadKey ();
28}
Running result:
The Result attribute is obtained only after Task 1 is run. Therefore, Task 2 starts to run only after Task 1 is run, that is to say, the values of the preceding two results will not change no matter how many times they are run. You can also use CurrentId to obtain the number of the currently running Task, but note that if we retrieve the number from the Task body, null is returned.