. Net 4 parallel (multi-core) programming Series II starts from task
We started to describe it step by step in a simple way, but we continue to do it in a step-by-step manner.
This articleArticleThe topics are as follows:
1. Basic Introduction to tasks
2. Create a task
3. Obtain the execution result of the task.
4. Additional details
Links to articles:
Introduction to one of. Net 4 parallel (multi-core) programming Series
. Net 4 parallel (multi-core) programming Series II starts from task
. Net 4 parallel (multi-core) programming Series 3 from task Cancellation
. Net 4 parallel (multi-core) programming Series 4 Task sleep
. Net parallel (multi-core) programming Series 5 task execution and Exception Handling
. Net parallel (multi-core) programming Series 6-task Basics
. Net parallel (multi-core) programming Series 7 shared data problems and solutions Overview
1. Basic Introduction to tasks
First, let's take a look at a simpleCode:
Here we only show a simple piece of code, which cannot show the characteristics of parallel programming. However, from the basic point of view, we will gradually enter a deeper topic.
If you have used it before. net multi-thread programming. After a comparison, we will find that although the Code uses multiple threads at the underlying layer, the writing is much simplified, and a line of code implements a parallel programming.
Let's start with the task class.
The task class is the core class in the task programming library (TPL). Next I will show you how to use some methods to create different types of tasks,
Cancel the task and wait until the task execution is completed. Obtain the result after the task execution and handle the exception.
Before starting the discussion, let's take a quick look at the previous Code:
This namespace will be frequently used in parallel programming later. This space contains many classes related to parallel programming.
Another namespace you want to use is: system. threading, you should be familiar with this. We often use this in the previous multi-threaded programming. This space contains some classes used to coordinate data in parallel programming.
In the above Code, the main code is as follows:
Task. Factory. startnew (() =>
{
Console. writeline ( " Hello World " );
});
We use the static method: task. Factory. startnew () to create a simple task-print a sentence on the screen. This code is indeed simple, and there is no input or result to be returned.
Next we will officially enter the topic:
2. Create a task
To create a simple task, we only need to provide an execution body for the task. The execution body can be a delegate or action. The code we showed earlier adopts a Lambda expression as the execution body of the task.
2.1 create a simple task
To execute a simple task, perform the following steps:
FirstTo create an instance of the task class,
ThenTo pass in a system. Action delegate. The method in this delegate is the method you want to execute when the task is running, and this delegate must be passed in as a parameter of the task constructor. There are multiple methods for passing in a delegate as a parameter: Passing in an anonymous delegate,
Lambda expressions or a delegate that shows the method.
Last, Call the START () method of the task instance to run the task.
When the task instance starts running, it is passed to an internal task scheduler, which is responsible for handing over the tasks we created to the bottom thread for execution.
Let's take a look at the Code:
Code
Using System;
Using System. Threading. tasks;
Namespace Listing_02
{
Class Listing_02
{
Static Void Main ( String [] ARGs)
{
// Use an action delegate and a named Method
Task 1 = New Task ( New Action (printmessage ));
// Use a anonymous delegate
Task 2 = New Task ( Delegate
{
Printmessage ();
});
// Use a Lambda expression and a named Method
Task 3 = New Task (() => Printmessage ());
// Use a Lambda expression and an anonymous method
Task 4 = New Task (() =>
{
Printmessage ();
});
Task1.start ();
Task2.start ();
Task3.start ();
Task4.start ();
// Wait for input before exiting
Console. writeline ( " Main method complete. Press enter to finish. " );
Console. Readline ();
}
Static VoidPrintmessage ()
{
Console. writeline ("Hello World");
}
}
}
I don't know if you have noticed it. The method for creating a task in the above Code is different from the method for creating a task in the first code. Previously we used task. factory. startnew () method is used to create a task and start running the task. In fact, the results of the code at both ends are the same. Here is a suggestion: If you want to create a task simply, use factory. newstart () is easy to create. If you add more customization and set specific attributes to the created task, we still need to follow the steps we mentioned step by step. (We will introduce it in detail later)
2.1 input parameters for the created task
We mentioned earlier that when creating a task, we input a system in the constructor. if we want to pass some parameters into the task, we can pass in the system. action <Object> delegate, where the object is the input parameter. Let's give you an example:
Code
Using System;
Using System. Threading. tasks;
Namespace Listing_04
{
Class Listing_04
{
Static Void Main ( String [] ARGs)
{
String [] Messages = { " First task " , " Second Task " ,
" Third Task " , " Fourth task " };
Foreach ( String MSG In Messages)
{
Task mytask = New Task (OBJ => Printmessage (( String ) OBJ), MSG );
Mytask. Start ();
}
// Wait for input before exiting
Console. writeline ( " Main method complete. Press enter to finish. " );
Console. Readline ();
}
Static VoidPrintmessage (StringMessage)
{
Console. writeline ("Message: {0}", Message );
}
}
}
Note: After passing in parameters, you must convert them to their original type and then call the corresponding method. In this example, because the method corresponding to system. Action is the printmessage () method, and the required parameter type of this method is string, it must be converted to string.
To input parameters to a task, you can only use system. Action <Object>
3. Obtain the execution result of the task.
If you want to obtain the result of a task, you must use the task <t> to instantiate a task when creating the task. The T is the type of the result returned after the task is executed. The result can be obtained by using the result attribute of the task instance.
The code is shown as follows:
Code
Static Void Main ( String [] ARGs)
{
// Create the task
Task < Int > Task1 = New Task < Int > (() =>
{
Int Sum = 0 ;
For ( Int I = 0 ; I < 100 ; I ++ )
{
Sum + = I;
}
Return SUM;
});
Task1.start ();
// Write out the result
Console. writeline ( " Result 1: {0} " , Task1.result );
Console. Readline ();
}
The result value can be obtained only after the task is executed.
The following code creates a task through task. Factory. startnew <t> () and obtains the result:
Code
Static Void Main ( String [] ARGs)
{
// Create the task
Task < Int > Task1 = Task. Factory. startnew < Int > (() =>
{
Int Sum = 0 ;
For ( Int I = 0 ; I < 100 ; I ++ )
{
Sum + = I;
}
Return SUM;
});
//Write out the result
Console. writeline ("Result 1: {0}", Task1.result );
Console. Readline ();
}
4. Additional details
When creating a task, the task has a lot of constructor overloading. A major overload is the input of taskcreateoptions enumeration:
Taskcreateoptions. None: Creates a task by default.
Taskcreateoptions. preferfairness: Request scheduler to execute the task as fairly as possible (in the future, the task will have the same priority as the thread)
Taskcreateoptions. longrunning: declares that a task will run for a long time.
Taskcreateoptions. attachtoparent: Because tasks can be nested, this enumeration is to attach a subtask to a parent task.
Finally, we can use task. currentid in the execution body of the task to return the unique ID (INT) of the task ). If this attribute is used in external tasks, null is obtained.
(Friends who are familiar with WF can compare the differences between tasks and WF, because I think they have similar design ideas)
This is today. Thank you!
The copyright is owned by Xiaoyang and the blog Park. for reprinting, indicate the source to the author.
Http://www.cnblogs.com/yanyangtian