background:
Previously wanted to use Semaphore to deal with the problem of concurrent access to resources, and later to show the scheme to the predecessors, they said this is OK, but it is better to use task processing, relatively simple. So, by the way, I learned the next task.
UseTaskclass to create and perform simple tasks
wait for the task to complete and get the return value
use the ContinueWith method to start a new task when the task is completed
Creating parent-child tasks and task factory usage
<span style= "FONT-SIZE:12PX;" >namespace Creating parent-child tasks and task factories using the {class Program {//task created through the task class is a top-level task that can be done by using TaskCreationOptions. The attachedtoparent identifies that these tasks are associated with creating his task//after all subtasks are completed the parent task ends the operation//static void Main (string[] args) { #region Create a parent-child task Demo//task<string[]> parent = new Task<string[]> (state = { Console.WriteLine (state); String[] result = new STRING[2]; Create and start a subtask//New Task (() = {Result[0] = "Task 1 ... ";},taskcreationoptions. attachedtoparent). Start (); New Task (() = {result [1]=] Task 2 ... ";},taskcreationoptions. attachedtoparent). Start (); return result; }, "Here is the parent task and create multiple subtasks during processing, and all child tasks will not be executed until after completion." "); Action//parent performed after task processing is complete. ContinueWith (t=>{//Array.foreach (T.result, R = Console.WriteLine (r)); // }); Start parent Task//parent. Start (); Console. ReadKey (); Use Task Parent=new Task (() =>{Cancellationtokensou for #endregion #region task factory Rce cts = new CancellationTokenSource ();//Why not include a constructor for a parameter?????? Create a task factory TaskFactory tf = new TaskFactory (CTS. Token, Taskcreationoptions.attachedtoparent, taskcontinuationoptions.executesynchronously, TaskScheduler.Default) ; Add a group of subtasks with the same state task[] task=new task[]{TF. StartNew (() =>{console.writeline ("I am the first task in the Mission Factory"), TF. StartNew (() =>{console. WriteLine ("I am the second task in the Mission Factory"), TF. StartNew (() =>{console. WriteLine ("I am the third task in the Mission Factory");}) }; }); Parent. Start (); Console.readkey (); #endregion}}}</span>
Implementation and scheduling within a task
Within a task, there is a set of properties that make up the status of the task, the unique ID of the task, the execution status of the task (TaskStatus), the reference to the callback function that is provided when the task is created, and the data object asyncstate that is passed to the callback function. A reference to the task dispatch object (TaskScheduler) when the task was created, a reference to the parent task, and a reference to the execution context and the ManualResetEventSlim object.
Both the task and task<tresult> classes implement a standard interface for freeing resources, allowing the Dispose method to release resources when the task finishes processing (Close the ManualResetEventSlim object instance). You can use the CurrentID property of the task class to get the ID of the task that is being executed, and if no task is performed currentid the value returned by Null,currentid is an int, the nullable type of the property. The life cycle of a task execution is represented by a value similar to TaskStatus, and TaskStatus contains a value of TaskStatus
namespace implementation and scheduling within the task {class program {static void Testdemo () {//Get Synchronization Context Task Scheduler Ta Skscheduler M_synccontexttaskscheduler = Taskscheduler.fromcurrentsynchronizationcontext ();// Represents a low-level work object that queues a task to a thread//creates a task and performs a task with the default task schedule (thread Pool Task Scheduler) task<int> tasks = new Task<int> (() = = {//perform complex computational Tasks Thread.Sleep (2000);//When the front-thread pauses the sum of int = 0; for (int i = 0; i < i++) {sum + = i; } return sum; }); var cts = new CancellationTokenSource (); When the task finishes, a successor task is started and the UI component task is updated with the synchronization Context Task Scheduler Schedule task. ContinueWith (T + = {Console.WriteLine) updates the UI with the Synchronizationcontexttaskscheduler Task Scheduler. \ r \ n The calculated result is: "+ task. Result.tostring ()); }, CTS. Token, Taskcontinuationoptions.attachedtoparent, M_synccontexttaskscheduler); Task. Start (); } Static VOID Main (string[] args) {Testdemo (); }} #region TaskStatus contains values://public enum TaskStatus//{//Created = 0,//waitingforact Ivation = 1,//Waitingtorun = 2,//Running = 3,//Waitingforchildrentocomplete = 4,//rantocom Pletion = 5,//Canceled = 6,//Faulted = 7//} #endregion}
We can get all the exceptions for the task during execution through the exception property of the Tasks class, exception is a aggregateexception type property. The task class provides iscanceled, IsCompleted, and isfaulted properties to get the completion status of a task. Subsequent tasks created through ContinueWith, Continuewhenall, Continuewhenany, and FromAsync are in the waitingforactivation state, and the tasks of this state are automatically executed when the parent task completes.
The execution of the task is dispatched internally by the TaskScheduler class, which is an abstract class, The FCL derives two derived classes from him: The Threadpooltaskscheduler thread Pool Task Scheduler and the Synchronizationcontexttaskscheduler Synchronization context Task Scheduler. All tasks default to the Threadpooltaskscheduler dispatch task, which uses a thread pool to perform tasks, and can obtain a reference to the default task scheduler through the static property default of the TaskScheduler class. Synchronizationcontexttaskscheduler Task Scheduler can be used in Windowform, WPF and other applications, his Task Scheduler is the GUI thread used, so he can synchronize update UI components, A reference to a synchronization context task schedule can be obtained by fromcurrentsynchronizationcontext the static method of the TaskScheduler class.
Multithreading--task