. Net4.0 Parallel programming (iii) under Data Parallelism

Source: Internet
Author: User

In the previous article, we introduced how to Break and Stop loops, and how to define local variables of a thread. This article describes how to cancel loops and handle exceptions externally.

Cancel

In a parallel loop, you can pass the aspx> CancellationToken in the ParallelOptions parameter to cancel loop control. We can pass CancellationTokenSource to the Cancellation value of the ParallelOptions object after instantiation. The following is an example:

 

01 [TestMethod]
02 public void CancelLoop()
03 {
04     var sourceNums = Enumerable.Range(0, 1000000000);
05     var cts = new CancellationTokenSource();
06     var po = new ParallelOptions();
07     var stack = new ConcurrentStack<int>();
08     po.CancellationToken = cts.Token;
09     po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;
10     Task.Factory.StartNew(() =>
11     {
12         foreach (var num in sourceNums)
13         {
14             if (num == 1000000)
15                 cts.Cancel();
16         }
17     });
18  
19     try
20     {
21         Parallel.ForEach(sourceNums,po, num => 
22         {
23             stack.Push(num);
24             po.CancellationToken.ThrowIfCancellationRequested();
25

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.