Thread pool-implements a cancellation option

Source: Internet
Author: User

Code Demo:

Using System;
Using System.Threading;

Add the following code snippet below the Main method:

static void AsyncOperation1 (CancellationToken token)
{
Console.WriteLine ("Starting the first task");
for (int i = 0; i < 5; i++)
{
if (token. iscancellationrequested)
{
Console.WriteLine ("The first task has been canceled.");
Return
}
Thread.Sleep (Timespan.fromseconds (1));
}
Console.WriteLine ("The first task has completed succesfully");
}
<summary>
///
</summary>
<param name= "token" ></param>
static void AsyncOperation2 (CancellationToken token)
{
Try
{
Console.WriteLine ("Starting the second task");

for (int i = 0; i < 5; i++)
{
Token. Throwifcancellationrequested ();
Thread.Sleep (Timespan.fromseconds (1));
}
Console.WriteLine ("The second task has completed successfully");
}
catch (operationcanceledexception)//Throw OperationCanceledException exception
{
Console.WriteLine ("The second task has been canceled.");
}
}
private static void AsyncOperation3 (CancellationToken token)
{
BOOL Cancellationflag = false;
Token. Register (() = Cancellationflag = True);//Register a callback function
Console.WriteLine ("Starting the third task");
for (int i = 0; i < 5; i++)
{
if (Cancellationflag)
{
Console.WriteLine ("The third task has been canceled.");
Return
}
Thread.Sleep (Timespan.fromseconds (1));
}
Console.WriteLine ("The third task has completed succesfully");
}

Add the following code snippet to the Main method:

using (var cts = new CancellationTokenSource ())
{
CancellationToken token = cts. Token;
ThreadPool.QueueUserWorkItem (_ = = AsyncOperation1 (token));
Thread.Sleep (Timespan.fromseconds (2));
Cts. Cancel ();
}

using (var cts = new CancellationTokenSource ())
{
CancellationToken token = cts. Token;
ThreadPool.QueueUserWorkItem (_ = = AsyncOperation2 (token));
Thread.Sleep (Timespan.fromseconds (2));
Cts. Cancel ();
}

using (var cts = new CancellationTokenSource ())
{
CancellationToken token = cts. Token;
ThreadPool.QueueUserWorkItem (_ = = AsyncOperation3 (token));
Thread.Sleep (Timespan.fromseconds (2));
Cts. Cancel ();
}
Thread.Sleep (Timespan.fromseconds (2));

Working principle:

The CancellationTokenSource and CancellationToken two new classes are described in this section. They're in. NET4.0 is introduced and is currently the de facto standard for canceling operations that implement asynchronous operations. Because the thread pool has been around for a long time and there is no special API to implement the unmark feature, the API can still be used on the thread pool.

There are three ways to implement the cancellation process in this program. The first one is polling to check the Cancellationtoken.iscancellationrequested property. If this property is true, then the operation needs to be canceled and we must discard the operation.

The second way is to run out of a operationcanceledexception exception. This allows you to control the cancellation process outside of the operation, which is handled by code other than the operation when the operation needs to be canceled.

The last way is to register a callback function. When the operation is canceled. , the online pool will call the callback function. This allows chaining to pass one cancellation logic into another asynchronous operation.

Thread pool-implements a cancellation option

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.