Write it in front.
Have to say 4.0 inside the new task is really refreshing, once in thread to find when the thread abort and so on when there is no corresponding event, just like the GridView in the paging, binding will produce events, but in the thread is not found. However, these are all implemented in the task, although not in the way of events, but it is actually implemented. That's exciting.
I. Overview
In the previous article. NET4.0 multithreaded Programming---Cooperative cancellation mentions that the thread pool does not provide any intrinsic means of telling us when the operation is finished, and we have no way to get a return value after the thread has finished.
In order to compensate for these shortcomings, Microsoft in. NET4.0 The concept of tasks (Task), the following two methods produce the same result
ThreadPool.QueueUserWorkItem (Sum, 5); Use the thread pool new Task (Sum, 5). Start ();//Use Task
The thread pool above is operated by the CPU itself, and the task requires the program to manually go to start.
For a task, you can pass an action when using its constructor (to pass a function with no arguments above), pass action<object> (a function with parameters), and pass Cancelationtoken (to receive the canceled command, That's what it feels like, token.
Second, wait for a task to complete and get its execution results
To get execution results, we must construct a Task<tresult> object that TResult must match the return value of the method that is about to be bound. Waits for its wait method to be called. Wrote a small example.
Code NamespaceAlex.Net4MultiThread.MyTask {Internal ClassOwntask {
Public Static voidMain () {Task<Int>T= NewTask<Int>(n=Sum ((Int) n),10); T.start (); T.wait ();//wait for Console.WriteLine (T.result);//900 }Private Static IntSum (int n "{int sum = 0; for (n < 100++10+= 10; } return sum;}}
} /span>
In the above code, if the task has already started executing when you call wait, the program prevents the current thread from waiting until the task finishes (as if it were a thread). When you call wait, the task does not start executing, and the thread is not blocked.
When an exception is generated in a task, the task returns normally, but the system throws a System.aggregateexception exception when the wait or result is called.
Third, cancel a task
However, using CancellationTokenSource to cancel a task, if it is possible to cancel a task, the corresponding method should accept a CancellationToken parameter (for the notification to be canceled). On the code.
Code NamespaceAlex.Net4MultiThread.MyTask {Internal ClassOwntask {
Public Static voidMain () {CancellationTokenSource cts= NewCancellationTokenSource (); Task<Int>T= NewTask<Int>(()=Sum (CTS. Token,10), CTS. Token);
T.start (); Cts. Cancel ();//Cancel Try{//The exception in the target operation is returned when wait or result is called Console.WriteLine (T.result);//900 }Catch(AggregateException ex) {Ex. Handle (E=EIsOperationCanceledException); Console.WriteLine ("Sum was canceled"); } }Private Static IntSum (CancellationToken CT,IntN) {Int= 0for (n < 100++) {Ct. Throwifcancellationrequested (); // sum += 10; } return sum;}}
The above operation is really exciting, it is very good compared to the thread.abort. For cancellation. If the task does not start at the time of cancellation, the task will not execute.
Iv. automatically start a new task when other tasks are completed
In the previous example, we wait for a task or to get the result of a task, which actually costs the system resources, in the task programming mode, most of the time we do not have to wait, just register a new task, the task is executed when the current task completes, At this point we can manipulate the result.
Code NamespaceAlex.Net4MultiThread.MyTask {Internal ClassOwntask {
Public Static voidMain () {Task<Int>T= new Task<int>< Span style= "color: #000000;" > (N=>sum (int< Span style= "color: #000000;" ) n), 10 T.start (); = T. ContinueWith (Task => Console.WriteLine ( "the sum is: " +Task. Result));//900 Console.read (); }Private Static intint N) {int sum = 0for (n < 100+++= 10; } return sum;}}
The new task (registration) in the code above is done through ContinueWith, which also returns a task, but generally ignores its return value directly, but should focus on its logic, "register what, what the registered task does, and when it should be executed ..." , for example, in the example above, the registered task prints out the execution result of the primary task at the end of the primary task.
In fact, the above code is executed after the main task completes a registered task, in fact, the ContinueWith function also accepts a Taskcontinuationoptions enumeration parameter. There are 8-9 values, I mainly show 3, the specific function as shown in its name.
Code T.continuewith (Task=Console.WriteLine ("The sum is:"+Task. Result), taskcontinuationoptions.onlyonrantocompletion);//Executes the currently generated task when the primary task succeeds T.continuewith (Task=Console.WriteLine ( "the sum is: " + task. Result), taskcontinuationoptions.onlyonfaulted); // T.continuewith (Task => Console.WriteLine ( "the sum is: + task. Result), taskcontinuationoptions.onlyoncanceled); // main task cancels execution of the currently generated task
NET4.0 Multithreaded Programming---Tasks