C #. Net parallel and multi-threaded programming Task learning records !,

Source: Internet
Author: User

C #. Net parallel and multi-threaded programming Task learning records !,

Difference between Task and Thread:

1. The task is structured on the thread, that is to say, the task should be finally thrown to the thread for execution.

2. Tasks and threads are not in a one-to-one relationship. For example, opening 10 tasks does not mean that 10 threads will be opened. This task is similar to the thread pool, however, tasks have little overhead and precise control over the thread pool.

The Task and Thread are in the same namespace as the System. Threading!

1. Create a Task

// Method 1: directly instantiate var task1 = new Task () =>{// TODO you code });
// Method 2: The Factory creates var task2 = Task. Factory. StartNew () =>{// TODO you code });

Ii. Simple lifecycle of a Task:

Created: indicates the default initialization task, but the "factory Created" instance is skipped directly.
WaitingToRun: this status indicates waiting for the task scheduler to allocate a thread to the task for execution.
RanToCompletion: the task is completed.

Iii. Task Control

The most attractive part of a Task is its control of the task. You can control the execution sequence of the task and make the tasks work in an orderly manner. The following is a detailed description:

1. Task. Wait

Task1.Wait (); wait for Task 1 to complete, and Task 1 to complete.

2. Task. WaitAll

You can simply see that it is waiting for all tasks to be completed:

{...

Task.WaitAll(task,task2,task3...N)
Console.WriteLine("All task finished!");
}
That is, when All tasks of task 2, task k3... N are executed, the code is executed ("All task finished!" is printed !")
3. Task. WaitAny

This is used to send the same Task. WaitAll, that is, wait for any Task to complete and continue to execute, replace the above Code WaitAll with WaitAny

{...

Task.WaitAny(task,task2,task3...N)
Console.WriteLine("Any task finished!");
}
That is, when all tasks of task 2, task k3... N are executed, the code is executed ("Any task finished!" is printed !")

4. Task. ContinueWith
The next Task is automatically started after the first Task is completed to implement the continuation of the Task. Let's take a look at its usage and write the following code:
      static void Main(string[] args){var task1 = new Task(() =>{Console.WriteLine("Task 1 Begin");System.Threading.Thread.Sleep(2000);Console.WriteLine("Task 1 Finish");});var task2 = new Task(() =>{Console.WriteLine("Task 2 Begin");System.Threading.Thread.Sleep(3000);Console.WriteLine("Task 2 Finish");});task1.Start();task2.Start();var result = task1.ContinueWith<string>(task =>{Console.WriteLine("task1 finished!");return "This is task result!";});Console.WriteLine(result.Result.ToString());Console.Read();}


We can see that after task 1 is complete, we start to execute the following content, and here we get the return value of the task.
5. Cancel a Task

We have discussed the usage of so many tasks. For example, we have started a Task, encountered an exception, or clicked to cancel the Task. We can cancel the task. How to cancel a Task? We use the tokens of cancellation to cancel a Task. The Body of many tasks contains loops. we can judge whether the IsCancellationRequested attribute is True during polling. If it is True, return or throw an exception. If it is thrown, we will discuss it later, because there is no exception handling.

The following code shows how to cancel a task:

Var tokenSource = new CancellationTokenSource (); var token = tokenSource. token; var task = Task. factory. startNew () => {for (var I = 0; I <1000; I ++) {System. threading. thread. sleep (1000); 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 started, a method is registered for the token, and a message is output. Then, run the ReadKey command to wait for the user to enter the method. After the user clicks enter, run the tokenSource. Cancel Method to Cancel the Task.
More information: Task class
Materials are collected on the network. If you have any biased understanding, please reply and correct it!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.