Task usage Summary

Source: Internet
Author: User

Task usage Summary

I. Sample Code for capturing tasks, multithreading, and exceptions:

Static void Main (string [] args) {// class that generates CancellationToken. This class allows the Cancel Method to terminate the thread. // you can also use CancellationTokenSource. createLinkedTokenSource: create a group of related tokens. If any of the cancellation items is canceled, CancellationTokenSource ts = new CancellationTokenSource (); CancellationToken ct = ts. token; Task t = null; t = new Task () => {for (int I = 1; I <11; I ++) {// call the Cancel method, status: true (meaning canceled) if (! Ts. IsCancellationRequested) {if (I = 5) {// this Exception is not directly captured by the main thread throw new Exception ("the number is 5, illegal! ") ;}} Else {Console. writeLine ("User canceled"); // throws an exception and forcibly cancels the subthread ct. throwIfCancellationRequested ();} Console. writeLine (I); Thread. sleep (500) ;}}, ct); t. start (); // events triggered after Cancel is registered. Note that Exception can also be captured here. continueWith (task) => {// The Console is set to True only when the Cancel method is called. writeLine (t. isCanceled); // no matter what the situation is, as long as the completion is True Console. writeLine (t. isCompleted); // if there is an exception, the value is True (even if it is ThrowIfCancellationRequested exception) Console. writeLine (t. isFaulted); // catch a variety of exceptions foreach (var item in task. exception. innerExceptions) {Console. writeLine (item. message) ;}}); Console. readLine (); // cancel the task ts. cancel (); Thread. sleep (Timeout. infinite );}

Conclusion:

1. All exceptions end with subthreads.

2. After an exception occurs, only the Wait/WaitAll/WaitAny/Result or Continue method of the Task can capture the exception. The main thread is impossible because it is an exception in the subthread.

Ii. Sequence of tasks (nested tasks allowed ), at the same time, the Thread can be mounted to the main Thread to execute the returned results (to avoid the previous Thread and WinForm control interaction "not created by this Thread control exception ......" Problem ):

Static void Main (string [] args) {CancellationTokenSource cts = new CancellationTokenSource (); CancellationToken ct = cts. token; Task t = new Task () => {Console. writeLine ("Director started ......, Contains three subtasks: "); Task. factory. startNew () => {Thread. sleep (1, 2000); Console. writeLine ("Task 1") ;}, // It is attached to the main thread, so that the main thread automatically waits for the completion of the subthread to complete TaskCreationOptions. attachedToParent); Task. factory. startNew () => {Thread. sleep (1, 500); Console. writeLine ("Task 2") ;}, TaskCreationOptions. attachedToParent); Task. factory. startNew () => {Thread. sleep (1, 1000); Console. writeLine ("Task 3") ;}, TaskCreationOptions. attachedToParent);}, ct); T. ContinueWith (Task) => {Console. WriteLine ("sub-tasks are completed, and the director's affairs are completed. "); // Specifies the synchronization block of the context to prevent cross-thread access to the control (console programs are not available, WinForm is acceptable)}, TaskScheduler. fromCurrentSynchronizationContext (); t. start (); Thread. sleep (Timeout. infinite );}

Compared with the original Wait, the sub-thread is not stuck and can run multiple tasks.

Want to know

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.