Multi-thread -- Task, multi-thread task

Source: Internet
Author: User

Multi-thread -- Task, multi-thread task




Background:

I used to use Semaphore to deal with the problem of concurrent resource access. When I showed the solution to my predecessors, they said it would work, but it is better to use tasks for processing. So I learned the Task by the way.



Use the task class to create and execute simple tasks







Wait until the task is completed and obtain the returned value







Start a new task when the task is completed using the ContinueWith Method






Create a parent-child task and use a job factory



<Span style = "font-size: 12px;"> using namespace to create parent and child tasks and task factories {class Program {// tasks created through the task class are top-level tasks, you can use TaskCreationOptions. attachedToParent identifies the tasks associated with the tasks to be created. // after all the sub-tasks are completed, the parent task will end the operation. // static void Main (string [] args) {# region create a parent and child Task Demo // Task <string []> parent = new Task <string []> (state = >{// Console. writeLine (state); // string [] result = new string [2]; // create and start a Task // new Task (() => {result [0] = "task 1... ";}, TaskCreationOptions. AttachedToParent). Start (); // new Task () =>{ result [1] =" Task 2... ";}, TaskCreationOptions. attachedToParent ). start (); // return result; //}, "this is the parent task, and multiple subtasks are created during the processing. All subtasks are executed only after they are completed. "); // The operation executed after the task is processed // parent. continueWith (t => {// Array. forEach (t. result, r => Console. writeLine (r); //}); // start the parent task // parent. start (); // Console. readKey (); # endregion # Use Task parent = new Task () => {CancellationTokenSource cts = new CancellationTokenSource (); // Why is the constructor that does not contain a parameter ?????? // Create a job factory TaskFactory tf = new TaskFactory (cts. token, TaskCreationOptions. attachedToParent, TaskContinuationOptions. executeSynchronously, TaskScheduler. default); // Add a group of subtasks in the same status [] Task = new task [] {tf. startNew () => {Console. writeLine ("I am the first task in the task factory");}), tf. startNew () => {Console. writeLine ("I am the second task in the job factory");}), tf. startNew () => {Console. writeLine ("I am the third task in the job factory") ;}};}); parent. start (); Console. readKey (); # endregion }}</span>


Internal implementation and scheduling of tasks


A task contains a group of attributes that constitute the task status, indicating the unique ID of the task and the task execution status ), the Data Object AsyncState provided by the callback function during Task creation and passed to the callback function. It references the task scheduling object (tasksched) During task creation, references to parent tasks, execution context, and ManualResetEventSlim objects.


The Task and Task <TResult> classes both implement the standard resource Release Interface, allowing you to use the Dispose method to release resources when the Task completes processing (disabling ManualResetEventSlim object instances ). You can use the CurrentID attribute of the Task class to obtain the ID of the Task being executed. If no Task is executed, the returned value of CurrentID is null. currentID is an int and can be empty. The life cycle of a task is represented by a value similar to TaskStatus. The value of TaskStatus is taskstatus.



Internal implementation and scheduling of the namespace task {class Program {static void TestDemo () {// obtain the TaskScheduler m_syncContextTaskScheduler = TaskScheduler. fromCurrentSynchronizationContext (); // indicates a low-level work object in which the task is queued to the thread for processing. // create the task and use the default Task Scheduling (thread pool Task Scheduler) execute the Task <int> task = new Task <int> () = >{// execute the complex computing Task Thread. sleep (2000); // The current thread suspends 2000 int sum = 0; for (int I = 0; I <100; I ++) {sum + = I ;} return sum;}); var cts = new Canc EllationTokenSource (); // when the task is completed, start a subsequent task and use the synchronization context task Scheduler to schedule the task to update the UI component task. continueWith (t => {Console. writeLine ("uses the SynchronizationContextTaskScheduler Task Scheduler to update the UI. \ R \ n: "+ task. result. toString ();}, cts. token, TaskContinuationOptions. attachedToParent, m_synccontexttaskschedent); task. start () ;}static void Main (string [] args) {TestDemo () ;}# value of region TaskStatus: // public enum TaskStatus // {// Created = 0, // WaitingForActivation = 1, // WaitingToRun = 2, // Running = 3, // WaitingForChildrenToComplete = 4, // RanToCompletion = 5, // Canceled = 6, // Faulted = 7 //} # endregion}


We can use the Exception attribute of the Task class to obtain all exceptions during Task execution. Exception is an attribute of the aggresponexception type. The Task class provides the IsCanceled, IsCompleted, and IsFaulted attributes to obtain the Task completion status. Subsequent tasks created through ContinueWith, ContinueWhenAll, ContinueWhenAny, and FromAsync are in the WaitingForActivation status. tasks in this status are automatically executed after the parent task is completed.

 

The task is executed by TaskScheduler class scheduling tasks. This class is an abstract class. FCL derives two Derived classes: ThreadPoolTaskScheduler thread pool task scheduler and SynchronizationContextTaskScheduler synchronous context Task Scheduler. All tasks use ThreadPoolTaskScheduler to schedule tasks by Default. The thread pool is used to execute tasks. You can use the static attribute Default of the TaskScheduler class to obtain references to the Default Task Scheduler. The SynchronizationContextTaskScheduler task scheduler can be used in Windowform, WPF, and other applications. Its job scheduling is a GUI thread, so it can synchronously update the UI component, you can use the static method FromCurrentSynchronizationContext of the taskschedationclass to obtain reference for scheduling a synchronization context task.




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.