Multithread programming learning notes-parallel task library (1), multithread programming learning notes
Multi-thread programming learning notes-basics (1)
Multi-thread programming learning notes-basics (2)
Multi-thread programming learning notes-basics (3)
Multi-thread programming learning notes-thread synchronization (1)
Multi-thread programming learning notes-thread synchronization (2)
Multi-thread programming learning notes-thread synchronization (3)
Multi-thread programming learning notes-Thread Pool (1)
Multi-thread programming learning notes-Thread Pool (2)
Multi-thread programming learning notes-Thread Pool (3)
We learned what threads are and how to use thread pools for synchronization between threads. Using the thread pool can reduce the operating system resources used by parallel threads for a large number of short-term operations.
In net framework 4.0, Microsoft provides a new asynchronous operation function called the task parallel Library (TPL ). Task is the core of the task parallel library ). A task represents an asynchronous operation, which can be run in multiple ways or without independent threads.
One Task can be combined with other tasks in multiple ways. For example, you can enable multiple tasks at the same time, wait for all tasks to complete, and then start another task for operations. A task can be composed of multiple other tasks. These tasks can also have their own subtasks in turn.
C #5.0 and later versions have built-in support for TPL, allowing us to execute tasks using the await and async keywords.
In the following example, we use a later version of. Net Framework 4.5.
1. Create a task
In the following example, we use the task constructor to create two tasks. We passed in a lambda expression as an operation task. Start the task with start.
Then, we use the task. Run and task. startNew methods to Run two tasks. Unlike the task constructor, the two created tasks are executed immediately. Therefore, you do not need to explicitly call the Start method of these tasks. All tasks from Task 1 to Task 4 are executed in the thread pool. The execution sequence is different after multiple executions.
Task5, because we mark it as a long run, it is a separate thread, not a thread in the thread pool.
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; using System. threading. tasks; namespace ThreadTPLDemo {class Program {static void Main (string [] args) {Console. writeLine ("Task running example ---- {0}", DateTime. now); var task1 = new Task () => taskdetail( "Task1"); var task2 = new Task () => taskdetail( "Task2 ")); task1.Start (); task2.Start (); Task. factory. startNew () => tasktasks ("Task 3"); Task. run () => tasktasks ("Task 4"); // Run the Task for a long time. factory. startNew () => taskdetail( "Task 5"), TaskCreationOptions. longRunning); Thread. sleep (1, 1000); Console. readKey ();} private static void taskdetail( string name) {Console. writeLine ("the Task runs on Thread ID: {0}. Is this Thread in the Thread pool Thread: {1}, name: {2}", Thread. currentThread. managedThreadId, Thread. currentThread. isThreadPoolThread, name );}}}
2. The running result is shown in. I ran the program twice. Check the differences.
Ii. Perform basic operations using tasks
In this example, the result value is obtained from the task. Different execution results show the differences between execution in the thread pool and execution in the main thread.
1. The Code is as follows:
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; using System. threading. tasks; namespace ThreadTPLDemo {class Program {static void Main (string [] args) {Console. writeLine ("basic Task operations ----"); taskdetail( "---- main thread Task running"); Task <string> task1 = CreateTask ("Task1"); task1.Start (); string result = task1.Result; Console. writeLine ("running result -- {0}", result ); Task <string> task2 = CreateTask ("Task2"); task2.RunSynchronously (); result = task1.Result; Console. writeLine ("running result -- {0}", result); Task <string> task3 = CreateTask ("Task3"); task3.Start (); while (! Task3.IsCompleted) {Console. writeLine ("status -- {0}", task3.Status); Thread. sleep (500);} Console. writeLine ("-- Status-{0}", task3.Status); result = task3.Result; Console. writeLine ("running result -- {0}", result); Console. readKey ();} private static string taskdetail( string name) {Console. writeLine ("Task Thread ID: {0}, is it a Thread in the Thread pool: {1}, name: {2}", Thread. currentThread. managedThreadId, Thread. currentThread. isThreadPoolThread, name); Thread. sleep (2000); return string. format ("Thread ID: {0}, name: {1}", Thread. currentThread. managedThreadId, name);} static Task <string> CreateTask (string name) {return new Task <string> () => taskdetail( name ));}}}
2. The program running result is shown in.
First, run the taskdetailmethod directly. Based on the program running result, we can know that this method is executed synchronously.
Then we run Task 1, start the task using the start method, and wait for the result. This task will be run in the thread pool, and the main thread will wait until the task ends and return results.
Task 2 is similar to Task 1. Task 2 runs through the RunSynchronously () method. This task runs in the main thread. The output of this task is the same as that of the taskdetailmethod. This is the advantage of the task. You can use the task to optimize the taskdetailmethod, and avoid using the thread pool to execute some very short operations.
Task 3 runs the Task 1 method, but this time the main thread is not blocked, but the task status is printed cyclically before the task is completed.