取消并行代码

需要让并行代码支持取消

using System;
using System.Text;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;

namespace Test
{
    class Program
    {
        public static string DateTime_Now_ToString()
        {
            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private static int Work(int index)
        {
            Thread.Sleep(1000);

            return index;
        }


        private static CancellationTokenSource cts = new CancellationTokenSource(5000);

        /// <summary>
        /// 取消并行代码
        /// </summary>
        static void Main()
        {
            try
            {
                var list = Enumerable.Range(1, 50);

                //1
                var query = list.AsParallel().WithCancellation(cts.Token)
                    .Select(item => Work(item));

                foreach (var item in query)
                {
                    Console.WriteLine(item);
                }


                //2
                Parallel.ForEach(list,
                    new ParallelOptions { CancellationToken = cts.Token },
                    item => { Thread.Sleep(1000); Console.WriteLine(item); });
            }
            //catch (OperationCanceledException e) { Console.WriteLine("{0}\n异常时间:{1}", e.ToString(), DateTime_Now_ToString()); }
            catch (AggregateException ae)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendLine("任务异常信息:");

                //Handle = Func<Exception,bool>
                ae.Handle(e =>
                {
                    //builder.AppendLine(String.Format("{0},{1}", e.ToString(), DateTime.Now.ToString()));
                    builder.AppendLine(String.Format("{0},{1}", e.Message, DateTime.Now.ToString()));
                    return true;
                });

                Console.WriteLine(builder.ToString());
            }
            catch (OperationCanceledException e) { Console.WriteLine("{0}\nCanceled异常时间:{1}", e.ToString(), DateTime_Now_ToString()); }
            catch (Exception e) { Console.WriteLine("{0}\n异常时间:{1}", e.ToString(), DateTime_Now_ToString()); }

            Console.WriteLine("\n执行完成");
            Console.ReadLine();
        }
    }
}

 

打印运行结果:

/*
System.OperationCanceledException: 已通过提供给 WithCancellation 的标记取消了查
询。
   在 System.Linq.Parallel.CancellationState.ThrowWithStandardMessageIfCanceled(
CancellationToken externalCancellationToken)
   在 System.Linq.Parallel.QueryOpeningEnumerator`1.MoveNext()
   在 Test.Program.Main() 位置 c:\实验室\DemoSolution\Test\Program.cs:行号 40
Canceled异常时间:2016-09-02 23:45:28

执行完成

*/

 

/*
5
2
3
1
4
7
6
8
9
10
11
12
16
13
15
14
17
18
20
22
24
26
28
19
21
27
23
25
29
31
System.OperationCanceledException: 已取消该操作。
   在 System.Threading.Tasks.Parallel.PartitionerForEachWorker[TSource,TLocal](P
artitioner`1 source, ParallelOptions parallelOptions, Action`1 simpleBody, Actio
n`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal,
 Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
   在 System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IEnumerable`
1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState
, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithE
verything, Func`1 localInit, Action`1 localFinally)
   在 System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, Par
allelOptions parallelOptions, Action`1 body)
   在 Test.Program.Main() 位置 c:\实验室\DemoSolution\Test\Program.cs:行号 47
Canceled异常时间:2016-09-02 23:49:34

执行完成
 
*/

 

posted @ 2016-09-06 12:51  茗::流  阅读(197)  评论(0)    收藏  举报
如有雷同,纯属参考。如有侵犯你的版权,请联系我。