Multithreaded Programming Learning Notes-Task Parallel Library (iii)

Source: Internet
Author: User

Take the multithreaded Programming Learning note above--Task Parallel Library (i)

Take the multithreaded Programming Learning note above--Task Parallel Library (ii)

VI. implementation of cancellation options

This example learns how to implement a task-based asynchronous operation to cancel the process, and how to know that the task has been canceled before the task actually runs.

1. The code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespacethreadtpldemo{classProgram {Static voidMain (string[] args) {Console.WriteLine ("cancel operation implemented in task ... "); varCTS =NewCancellationTokenSource (); varTask1 =Newtask<int> (() = RunTask ("Task 1",Ten, CTS. Token), CTS.                          Token); Console.WriteLine ("--task1 Status-{0}", Task1.            Status); Cts.                     Cancel (); Console.WriteLine ("--Cancel--task1 status-{0}-", Task1.                                 Status); Console.WriteLine ("--task1 operation canceled before error-"); //Task1. Start ();CTS =NewCancellationTokenSource (); varTask2 =Newtask<int> (() = RunTask ("Task 2",Ten, CTS. Token), CTS.            Token); Task2.            Start ();  for(inti =0; I <5; i++) {Thread.Sleep ( -); Console.WriteLine ("--task2 Status-{0}", Task2.            Status); } CTS.            Cancel ();  for(inti =0; I <5; i++) {Thread.Sleep ( -); Console.WriteLine ("--task2 Status-{0}", Task2.            Status); } Console.WriteLine ("--Mission task run result-{0}", Task2.            Result); Thread.Sleep ( -);         Console.read (); }         Private Static intRunTask (stringNameintSeconds,cancellationtoken token) {Console.WriteLine ("Task {0} running thread ={1}, whether the pool is online: {2}", Name,
Thread.currentthread.managedthreadid,thread.currentthread.isthreadpoolthread); for(inti =0; i < seconds; i++) {Thread.Sleep (Timespan.fromseconds (1)); if(token.) iscancellationrequested) {//cancels the operation, returns-1; return-1; } } return the*seconds; } }}

2. Program operation results such as.


First we look at Task1 's creation code, we pass a cancellation flag to the underlying task, and then pass the constructor of the task once again.

So why pass the two cancellation flag?

Because if it is canceled before the task actually starts, the bottom of the TPL is responsible for handling the cancellation. A task that has been processed by the TPL underlying the cancel operation throws an exception if it is started again. Such as.

Then we need to write our own code processing cancel operation, after canceling the operation, the state of the task is still rantocompletion, from the TPL point of view, this task has been completed.

VII. handling Exceptions in a task

In this example, we learn how to throw different cases of exceptions in a task, and how to obtain these exception information.

1. The program code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespacethreadtpldemo{classProgram {Static voidMain (string[] args) {Console.WriteLine ("handling exception information in a task ..... "); Try            {                varTask1 = Task.run (() = RunTask ("Task 1",2)); intresult =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 { varTask2 = Task.run (() = RunTask ("Task 2",2)); intresult =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 ("——————————————————————"); varTASK3 =Newtask<int> (() = RunTask ("Task 3",2)); varTASK4 =Newtask<int> (() = RunTask ("Task 4",2)); varCompletetaskall =Task.whenall (TASK3, TASK4); varException = Completetaskall.continuewith (t = Console.WriteLine ("--task error message-{0}", T.exception)
, taskcontinuationoptions.onlyonfaulted); Task3. Start (); Task4. Start (); Thread.Sleep (7000); Console.read (); } Private Static intRunTask (stringNameintseconds) {Console.WriteLine ("Task {0} running thread ={1}, whether the pool is online: {2}", Name,
Thread.currentthread.managedthreadid,thread.currentthread.isthreadpoolthread); Thread.Sleep (timespan.fromseconds (seconds)); Throw NewException ("Test the error message! "); return the*seconds; } }}

2. Program run results, such as.

When the program starts, create a task Task1 and try to get the results synchronously. The get portion of the result property causes the current thread to wait until the task finishes and propagates the exception to the current thread. In this case, it is easy to catch an exception with a catch block, but the exception is an encapsulation exception. So you can access innerexception to get exception information.

Task2 uses Getawaiter and getresult to get task results. In this case, you do not need to encapsulate the exception, and the TPL extracts the exception. If there is only one task at the bottom, only one exception is fetched at a time.

The last example is the case where two tasks (TASK3,TASK4) throw exceptions. This follow-up will only be triggered if there is an exception before the previous task is completed by handling the exception. Implemented by passing the taskcontinuationoption.onlyorfaulted option for subsequent operations, two exceptions were encapsulated in the thrown exception.

Multithreaded Programming Learning Notes-Task Parallel Library (iii)

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.