Preface: We step-by-step from the simple beginning to tell, or follow the way I have been: slowly evolving, step-by-step.
The topics in this article are as follows:
1.Task Basic Introduction
Creation of 2.Task
3. Get execution result of task
4. Supplementary details
1.Task Basic Introduction
First, let's take a look at a simple piece of code:
Here is a simple piece of code that doesn't show the characteristics of parallel programming. But we still start from the basic beginning, slowly into a deeper topic.
If you have ever used the multithreaded programming in. NET, compare it, you will find: This code, although at the bottom or the use of multiple threads, but the wording is simplified a lot, a line of code to achieve a parallel programming.
Now let's start with the task class.
The task class is one of the core classes in the Task Programming Library (TPL), and I'll show you how to use some methods to create different types of tasks.
Cancels a task, waits for task execution to complete, obtains the result after the task executes and handles the exception.
Before we start the discussion, let's take a quick look at the previous code:
This namespace will be one that we later talk about in parallel programming that we often use. This space contains a lot of classes related to parallel programming.
Another namespace to use is: System.Threading, you should be familiar with this, before multithreaded programming is often used, this space contains some in parallel programming to coordinate the data of some classes.
The most important code in the above code is as follows:
Task.Factory.StartNew(() =>
{
Console.WriteLine("Hello World");
});
We use the static method: Task.Factory.StartNew () to create the simplest task--to print a sentence on the screen. This code is really simple, and there are no inputs and results that need to be returned.