Parallel programming has always been a commonplace topic.
Here's a record of TPL programming, which in net4.0 Microsoft has provided a parallel library in the multi-core era, the most common of which is the task
What is a task?
A task can be simply understood as a wrapper for a thread, exposing several interfaces to the outside, such as common Task.run, Task.Factory.StartNew; When a task is started, the application waits for the task to execute, but does not block the UI thread, in other words, I lose a task with a thread and let him execute it, and then I immediately go back to the UI thread and the thread runs out and tells the UI thread that I'm done, and then the following After executing the task, which is a new asynchronous mechanism for Microsoft
What two tasks can do, from a simple start 2.1 to take a time-consuming operation, such as IO, an operation that requires a network connection, or a calculation, we throw a method directly to the task to execute
such as: Task.Factory.StartNew (() =
{
Time-consuming operation
Console.WriteLine ("Hello World");
});
2.2 Throw an action to a task to get the result of the task execution completion
static void Main (string[] args)
{
Create the Task
task<int> Task1 = new Task<int> (() =
{
int sum = 0;
for (int i = 0; i <; i++)
{
sum + = i;
}
return sum;
});
Task1. Start ();
Write out the result
Console.WriteLine ("Result 1: {0}", Task1. Result);
Console.ReadLine ();
}
2.3 To the task execution of the method passed in the parameters, in fact, this basically useless, because the function to be executed itself can directly use parameters
such as; static void Main (string[] args)
{
String[] messages = {"First task", "Second task",
"Third task", "Fourth Task"};
foreach (string msg in messages)
{
Here Printmessage the required parameters can be used directly with MSG, so the task passed MSG is actually not much use,
Task MyTask = new Task (() = Printmessage (msg), MSG);
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 void Printmessage (String message)
{
Console.WriteLine ("Message: {0}", message);
}
2.4 If a task is required to run for a long time
Simply loop through the function body like a thread:
such as: Task.run (() =>{
while (true)
{
Loop body
}
});
2.5 task-related parameters 2.5.1 priority
Threads are prioritized, then how and how they are set: by constructor
Taskcreateoptions.none: Create a task in the default way
Taskcreateoptions.preferfairness: Request Scheduler to execute the task as fairly as possible (subsequent articles will be, task and thread-like, prioritized)
Taskcreateoptions.longrunning: Declares that the task will run for a long time.
Taskcreateoptions.attachtoparent: Because a task can be nested, this enumeration is to append a child task to a parent task.
Simple use of TPL asynchronous parallel programming