■ Task<T> 클래스 : 자식 태스크 실행하기

----------------------------------------------------------------------------------------------------

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);

----------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker

댓글을 달아 주세요