Task: cancels the restriction operation of asynchronous computing & capture exceptions in the task. The Task cancels asynchronous computing.

Source: Internet
Author: User

Task: cancels the operation restriction on Asynchronous computing and captures exceptions in the task. The Task cancels asynchronous computing.

Why: ThreadPool does not have a built-in mechanism to mark when the current thread is finished, nor does it obtain the returned value when the operation is completed. Therefore, a Task is introduced to manage asynchronous threads more accurately.

How: Use the TaskCreationOptions parameter of the constructor to control How to create a task. For details, see the enumerated values of this enumeration. The Task. Result attribute is used to obtain the Task execution Result. wait () can be called internally, for example, WaitAny () or WaitAll.

How can I cancel the restrictions on Asynchronous computing? That is to say, how to cancel the task in progress? (The authors who despise clr use complicated words such as "computing restrictions and operations .)

Instantiate the CancelletionTokenSource class, pass the object as a parameter to the Asynchronous Method, and call the ThrowIfCancellationRequested () of the object in the asynchronous method. If the Cancel () method of the object is called, the Asynchronous Method throws an exception OperationCanceledException, and uses try-catch to capture (aggresponexception) in the main thread to capture and handle the exception.

Class Program {static void Main (string [] args) {CancellationTokenSource cts = new CancellationTokenSource (); // CancellationTokenSource (3000); // no result is obtained 3 seconds later, this thread is canceled. Task <Int32> t1 = Task. Run () => sum (cts. Token, 10000), cts. Token); // input CancellationToken, which is the attribute of CancellationTokenSource. Cts. Cancel (); // cts. CancelAfter (3000); // If no result is obtained 3 seconds later, Cancel the thread. Try {Console. WriteLine ("t1 execution Result:" + t1.Result); // obtain the execution Result of t1 through Result.} Catch (aggresponexception ex) {ex. handle (e => e is OperationCanceledException); Console. writeLine ("sum canceled");} Console. readKey ();} private static int sum (CancellationToken ct, int p) {int sum = 0; while (p> 0) {ct. throwIfCancellationRequested (); Thread. sleep (500); // accumulate every half second. Checked // if the calculation in the region overflows, an exception {sum + = p;} p --;} return sum ;}} will be thrown ;}}

 

Running result: sum has been canceled.

The exception is successfully captured and processed.

However, I found that I cannot understand one thing.

1. If you use the CancellationTokenSource constructor public CancellationTokenSource (int millisecondsDelay); If you construct an instance object, try-catch cannot catch an exception.

2. If it is canceled through CanelAfter (TimeSpan delay), no exception is caught.

Through ILSpy, I found that both the appeal constructor method and the CanelAfter method call the Cancel () method, but why can't exceptions be caught?

I will further check the source code of ThrowIfCancellationRequested

public void ThrowIfCancellationRequested()        {            if (this.IsCancellationRequested)            {                this.ThrowOperationCanceledException();            }        }

However, the source code of the Cancel () method does not modify the attribute of this. IsCancellationRequested, which cannot be solved by any means.

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.