Multi-thread programming learning notes-parallel task library (III), multi-thread programming learning notes

Source: Internet
Author: User

Multi-thread programming learning notes-parallel task library (III), multi-thread programming learning notes

Multi-thread programming learning notes-parallel task library (I)

Multi-thread programming learning notes-parallel task library (2)

 

6. Enable the cancel Option

This example shows how to cancel a Task-based Asynchronous Operation and how to know whether the Task has been canceled before the Task runs.

1. The Code is as follows:

Using System; using System. collections. generic; using System. componentModel; using System. linq; using System. text; using System. threading; using System. threading. tasks; namespace ThreadTPLDemo {class Program {static void Main (string [] args) {Console. writeLine ("cancels a Task... "); Var cts = new CancellationTokenSource (); var task1 = new Task <int> () => RunTask (" Task 1 ", 10, cts. token), cts. token); Console. writeLine ("-- task1 status-{0}", task1.Status); cts. cancel (); Console. writeLine ("-- Cancel -- task1 status-{0}-", task1.Status); Console. writeLine ("-- Task 1 canceled the operation before an error-"); // task1.Start (); cts = new CancellationTokenSource (); var task2 = new Task <int> (() => RunTask ("Task 2", 10, cts. token), cts. token); task2.Start (); for (int I = 0; I <5; I ++) {Thread. sleep (1, 500); Console. writeLine ("-- task2 status-{0}", task2.Status);} cts. cancel (); for (int I = 0; I <5; I ++) {Thread. sleep (1, 500); Console. writeLine ("-- task2 status-{0}", task2.Status);} Console. writeLine ("-- Task running result-{0}", task2.Result); Thread. sleep (1, 2000); Console. read ();} private static int RunTask (string name, int seconds, CancellationToken token) {Console. writeLine ("Task {0} is running in thread = {1}, whether it is in thread pool: {2}", name,
Thread. currentThread. managedThreadId, Thread. currentThread. isThreadPoolThread); for (int I = 0; I <seconds; I ++) {Thread. sleep (TimeSpan. fromSeconds (1); if (token. isCancellationRequested) {// cancel the operation, return-1; return-1 ;}} return 42 * seconds ;}}}

 

2. The program running result is shown in.


First, let's take a look at the creation code of Task 1. We pass a cancellation sign to the underlying task, and then pass another cancellation sign to the task constructor.

Why do we need to pass the cancellation mark twice?

If the task is canceled before it is actually started, the bottom layer of TPL is responsible for processing the cancellation operation. If a task that has been canceled by the TPL underlying layer is restarted, an exception is thrown. For example.

 

 

Then we need to write our own code to handle the cancellation operation. After the cancellation operation, the task status is still RanToCompletion. From the TPL perspective, this task has been completed.

 

7. Handling exceptions in tasks

In this example, we will learn how to throw exceptions in different situations in tasks and how to obtain the exception information.

1. The program code is as follows:

Using System; using System. collections. generic; using System. componentModel; using System. linq; using System. text; using System. threading; using System. threading. tasks; namespace ThreadTPLDemo {class Program {static void Main (string [] args) {Console. writeLine ("handle exception information in Task ..... "); Try {var task1 = Task. run () => RunTask ("Task 1", 2); int result = task1.Result; Console. writeLine ("-- task1 status-{0} --- value = {1}", task1.Status, result);} catch (Exception ex) {Console. writeLine ("-- task1 error message-{0}; innerException -- {1}", ex. message,
Ex. InnerException = null? String. empty: ex. innerException. message);} Console. writeLine ("----------------------"); try {var task2 = Task. run () => RunTask ("Task 2", 2); int result = task2.GetAwaiter (). getResult (); Console. writeLine ("-- task2 status-{0} --- value = {1}", task2.Status, result);} catch (Exception ex) {Console. writeLine ("-- task2 error message-{0}", ex. message);} Console. writeLine ("----------------------"); var task3 = new Task <int> () => RunTask ("Task 3", 2 )); var task4 = new Task <int> () => RunTask ("Task 4", 2); var completeTaskAll = Task. whenAll (task3, task4); var exception = completeTaskAll. continueWith (t => Console. writeLine ("-- task error message-{0}", t. exception)
, TaskContinuationOptions. onlyOnFaulted); task3.Start (); task4.Start (); Thread. sleep (1, 7000); Console. read ();} private static int RunTask (string name, int seconds) {Console. writeLine ("Task {0} is running in thread = {1}, whether it is in thread pool: {2}", name,
Thread. CurrentThread. ManagedThreadId, Thread. CurrentThread. IsThreadPoolThread); Thread. Sleep (TimeSpan. FromSeconds (seconds); throw new Exception ("test error message! "); Return 42 * seconds ;}}}

 

2. The program running result, such.

 

When the program starts, create a task Task 1 and try to get the results synchronously. The Get part of the Result property will wait for the current thread until the task is completed and the exception is propagated to the current thread. In this case, the catch code block can easily catch exceptions, but this exception is an encapsulation exception. Therefore, you can access InnerException to obtain the exception information.

Task 2 uses GetAwaiter and GetResult to obtain the task result. In this case, no encapsulation exception is required, and TPL extracts the exception. If there is only one task at the underlying layer, only one exception is extracted at a time.

In the last example, two tasks (task3, task4) throw an exception. To handle exceptions, follow-up operations will be triggered only when exceptions occur before the previous task is completed. The TaskContinuationOption. OnlyOrFaulted option is passed in subsequent operations. Two exceptions are encapsulated in the thrown exception.

Related Article

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.