■ Task<T> 클래스를 사용해 자식 태스크를 실행하는 방법을 보여준다.
▶ 예제 코드 (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 |
using System; using System.Threading; using System.Threading.Tasks; #region 값 구하기 - GetValue(taskName) /// <summary> /// 값 구하기 /// </summary> /// <param name="taskName">태스크명</param> /// <param name="waitTime">대기 시간</param> /// <returns>값</returns> private int GetValue(string taskName, int waitTime) { Console.WriteLine ( "태스크명 : {0}, 스레드 ID :{1}, 스레드 풀 사용 여부 : {2}", taskName, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread ); Thread.Sleep(waitTime); return DateTime.Now.Millisecond; } #endregion Task<int> parentTask = new Task<int> ( () => { Task childTask = Task.Factory.StartNew ( () => GetValue("Child Task #1", 5000), TaskCreationOptions.AttachedToParent ); childTask.ContinueWith ( t => GetValue("Child Task #2", 2000), TaskContinuationOptions.AttachedToParent ); return GetValue("Parent Task", 2000); } ); parentTask.Start(); while(!parentTask.IsCompleted) { Console.WriteLine(parentTask.Status); Thread.Sleep(500); } Console.WriteLine(parentTask.Status); int value = parentTask.Result; Console.WriteLine("반환값 : {0}", value); Thread.Sleep(10000); |