■ 태스크 예외를 처리하는 방법을 보여준다.
▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
using System; using System.Threading; using System.Threading.Tasks; ... #region 테스트 처리하기 - Test(taskName, secondCount) /// <summary> /// 테스트 처리하기 /// </summary> /// <param name="taskName">태스크명</param> /// <param name="secondCount">초 카운트</param> /// <returns>처리 결과</returns> private static int Test(string taskName, int secondCount) { Console.WriteLine ( "[{0} 스레드] 실행 태스크 : {1}, 스레드 풀 스레드 여부 : {2}", Thread.CurrentThread.ManagedThreadId, taskName, Thread.CurrentThread.IsThreadPoolThread ); Thread.Sleep(TimeSpan.FromSeconds(secondCount)); throw new Exception("고의적인 예외"); // 실행되지 않는다. return secondCount; } #endregion ... Task<int> task; try { task = Task.Run(() => Test("태스크 1", 2)); int result = task.Result; Console.WriteLine("태스크 결과 : {0}", result); } catch(Exception exception) { Console.WriteLine("발생 예외 :"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine("Exception caught : {0}", exception); Console.WriteLine("--------------------------------------------------"); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); try { task = Task.Run(() => Test("태스크 2", 2)); int result = task.GetAwaiter().GetResult(); Console.WriteLine("태스크 결과 : {0}", result); } catch(Exception exception) { Console.WriteLine("발생 예외 :"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine("Exception caught : {0}", exception); Console.WriteLine("--------------------------------------------------"); } Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Task<int> task3 = new Task<int>(() => Test("태스크 3", 3)); Task<int> task4 = new Task<int>(() => Test("태스크 4", 2)); Task<int[]> task5 = Task.WhenAll(task3, task4); Task task6 = task5.ContinueWith ( t => { Console.WriteLine("발생 예외 :"); Console.WriteLine("--------------------------------------------------"); Console.WriteLine("Exception caught : {0}", t.Exception); Console.WriteLine("--------------------------------------------------"); }, TaskContinuationOptions.OnlyOnFaulted ); task3.Start(); task4.Start(); Thread.Sleep(TimeSpan.FromSeconds(5)); |