使用回调函数处理任务异常2
using System; using System.Text; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Test { class Program { public static string DateTime_Now_ToString() { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } private static void TaskMehodA() { Thread.Sleep(TimeSpan.FromSeconds(1)); throw new AggregateException("TaskA Exception"); } private static void TaskMehodB() { Thread.Sleep(TimeSpan.FromSeconds(2)); throw new NullReferenceException("TaskB Exception"); } private static void TaskMehodC() { Thread.Sleep(TimeSpan.FromSeconds(3)); cts.Cancel(); //throw new OperationCanceledException("TaskC Exception"); } private static CancellationTokenSource cts = new CancellationTokenSource(); /// <summary> /// 使用回调函数处理任务异常 /// </summary> static void Main() { CancellationToken token = cts.Token; try { Task taskA = Task.Factory.StartNew(TaskMehodA); //cts取消操作后,引用它的cts.Token都会引发OperationCanceledException异常 Task taskB = Task.Factory.StartNew(() => { Thread.Sleep(5000); token.ThrowIfCancellationRequested(); TaskMehodB(); }, cts.Token, TaskCreationOptions.None, TaskScheduler.Default); Task taskC = Task.Factory.StartNew(() => { TaskMehodC(); //token.ThrowIfCancellationRequested(); //该方法会检查是否要取消task,并抛出异常 if (token.IsCancellationRequested == true) { throw new OperationCanceledException(token);//在task运行体中抛出OperationCanceledException异常来取消运行的task } }, token, TaskCreationOptions.PreferFairness, TaskScheduler.Default); Task taskD = Task.Run(() => { Thread.Sleep(TimeSpan.FromSeconds(2)); throw new InvalidOperationException("TaskD Exception"); }); Task taskE = new Task(() => { Thread.Sleep(TimeSpan.FromSeconds(2)); throw new InvalidOperationException("TaskE Exception"); }); taskE.Start(); Task.WaitAll(taskA, taskB, taskC, taskD, taskE); } catch (AggregateException ae) { StringBuilder builder = new StringBuilder(); builder.AppendLine("任务异常信息:"); //Handle = Func<Exception,bool> ae.Handle(e => { builder.AppendLine(String.Format("{0},{1}", e.Message, DateTime.Now.ToString())); return true; }); Console.WriteLine(builder.ToString()); } catch (Exception e) { Console.WriteLine(e.Message); } Console.WriteLine("\n执行完成" + DateTime_Now_ToString()); Console.ReadLine(); } } }
打印运行结果:
/* 任务异常信息: TaskA Exception,2016/9/2 22:55:31 已取消一个任务。,2016/9/2 22:55:31 已取消一个任务。,2016/9/2 22:55:31 TaskD Exception,2016/9/2 22:55:31 TaskE Exception,2016/9/2 22:55:31 执行完成2016-09-02 22:55:31 */

浙公网安备 33010602011771号