整理: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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章