The task class is the newly added feature of. NET 4.0, which further encapsulates the original Thread,threadpool, making multithreaded programming on the. NET platform more convenient. Don't say much nonsense, get to the point.
A. Task start
Task initiation is mainly used in the following ways:
1. Construct the Task object, start the task
1 New Task (dosomething); 2 Mytask.start ();
2. Start a task by task.factory
Task second = Task.Factory.StartNew (dosomething);
The difference is that when a task is created, it needs to start with the Start method, and the Task.factory StartNew method launches the task directly without having to start it manually.
Parameters are typically a delegate,action or lambda expression that tells the task what method to execute.
In addition, the task and task.factory have two versions with return values, which are used for tasks with return values, as follows:
New New MyClass ()); Mytask.start ();
New MyClass ());
Two. Task return value (the generic version has a return value)
You can get the return value in the following ways (note that this action will block the current thread):
var result = Mytask.result;
If you want to get the current state of the thread, you can call the task's status property, which is an enumeration value.
Three. Task End
If you need to manually control the end of a task, Microsoft provides the CancellationTokenSource token class, using the following methods:
New CancellationTokenSource (); TaskNew task<myclass> (() =>{thread.sleep (); Returnnew MyClass ();},canceltokensource.token); Mytask.start (); Canceltokensource.cancel () ;
New CancellationTokenSource (); Task<MyClass> mytask = Task.Factory.StartNew (() = {Thread.Sleep ( New MyClass ();}, Canceltokensource.token); Canceltokensource.cancel ();
Ends the target task by the Cancel method.
The main points of the task are recorded here, and there is no shortage of places to add later.
Multithreaded Essay II (TASK)