■ EAP 패턴을 태스크로 변환하는 방법을 보여준다.
▶ 예제 코드 (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 |
using System; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; ... #region 테스트 처리하기 - Test(name, secondCount) /// <summary> /// 테스트 처리하기 /// </summary> /// <param name="name">명칭</param> /// <param name="secondCount">초 카운트</param> /// <returns>처리 결과</returns> private int Test(string name, int secondCount) { Console.WriteLine ( "[{0} 스레드] 처리명 {1}, 스레드 풀 스레드 여부 : {2}", Thread.CurrentThread.ManagedThreadId, name, Thread.CurrentThread.IsThreadPoolThread ); Thread.Sleep(TimeSpan.FromSeconds(secondCount)); return secondCount; } #endregion ... TaskCompletionSource<int> taskCompletionSource = new TaskCompletionSource<int>(); BackgroundWorker backgroundWorker = new BackgroundWorker(); backgroundWorker.DoWork += (sender, e) => { e.Result = Test("백그라운드 작업자", 5); }; backgroundWorker.RunWorkerCompleted += (sender, e) => { if(e.Error != null) { taskCompletionSource.SetException(e.Error); } else if(e.Cancelled) { taskCompletionSource.SetCanceled(); } else { taskCompletionSource.SetResult((int)e.Result); } }; backgroundWorker.RunWorkerAsync(); int result = taskCompletionSource.Task.Result; Console.WriteLine("처리 결과 : {0}", result); |