整理:Task异常补货方法

1、应用ContineWith

var task1 = Task.Run(() => { throw new Exception("task1 faulted."); }).ContinueWith(t =>{Console.WriteLine("{0}: {1}",t.Exception.InnerException.GetType().Name,t.Exception.InnerException.Message);},TaskContinuationOptions.OnlyOnFaulted); Thread.Sleep(500);

 

var testTask = TestAsync(5, -10);testTask.ContinueWith(task => {if (task.IsFaulted) {Console.WriteLine(task.Exception.GetBaseException());}else {Console.WriteLine(task.Result);}});

2、应用Wait       

try{Task t1 = Task.Factory.StartNew(() => {throw new Exception("执行失败");});//主线程等待,可以 捕捉异常t1.Wait();}catch (AggregateException ex){foreach (var item in ex.InnerExceptions){Console.WriteLine("异常类型:{0}{1}来自:  {2} {3} 异常内容:{4} ", item.GetType(),Environment.NewLine, item.Source,Environment.NewLine, item.Message);}Console.Write(ex.Message);}

参考连接:

https://www.cnblogs.com/tianma3798/p/7003862.html

https://www.cnblogs.com/Johar/p/9245029.html


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部