블로그 이미지
따시쿵

calendar

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

Notice

'비동기 작업 Task'에 해당되는 글 1

  1. 2015.01.10 Task 클래스
2015. 1. 10. 18:03 C#

비동기 작업을 나타냅니다.


다음 예제에서는 TaskFactory.StartNew 메서드를 사용하여 작업을 시작하는 방법을 보여 줍니다.


출처 : http://msdn.microsoft.com/ko-kr/library/system.threading.tasks.task(v=vs.110).aspx


실행 화면


예제 프로그램

// Expected results:
// 		Task t1 (alpha) is created unstarted.
//		Task t2 (beta) is created started.
//		Task t1's (alpha) start is held until after t2 (beta) is started.
//		Both tasks t1 (alpha) and t2 (beta) are potentially executed on 
//           threads other than the main thread on multi-core machines.
//		Task t3 (gamma) is executed synchronously on the main thread.

            Action<object> action = (object obj) =>
                {
                    Console.WriteLine("Task={0}, obj={1}, Thread={2}",
                        Task.CurrentId, obj.ToString(), Thread.CurrentThread.ManagedThreadId.ToString());
                };

            // Construct aun unstarted task
            Task t1 = new Task(action, "alpha");

            // Construct a started task
            Task t2 = Task.Factory.StartNew(action, "beta");

            // Block the main thread to demonstrate that t2 is executing
            t2.Wait();

            // Launch t1
            t1.Start();

            Console.WriteLine("t1 has been launched. (Main Thread={0})", Thread.CurrentThread.ManagedThreadId.ToString());

            // Wait for the task to finish
            t1.Wait();

            // Construct an unstarted task
            Task t3 = new Task(action, "gamma");

            // Run it synchronously
            t3.RunSynchronously();

            // Although the task was run synchronously. it is a good practice
            // to wait for it in the event exception were thrown by task.
            t3.Wait();

            // 프로그램 종료 방지
            Console.Read();



Task 를 만들어서 실행하는 방법들을 설명합니다.


실행 화면



예제 프로그램


        static void Main(string[] args)
        {
            // use an Action delegate and named method
            Task task1 = new Task(new Action(printMessage));

            // use an anonymous delegate
            Task task2 = new Task(delegate { printMessage(); });

            // use a lambda expressiion and a named method
            Task task3 = new Task(() => printMessage());

            // use a lambda expression and an anonymous method
            Task task4 = new Task(() => { printMessage(); });
            
            task1.Start();
            task2.Start();
            task3.Start();
            task4.Start();

            Console.WriteLine("Main method complete. Press <enter> to finish");
            Console.WriteLine("Main Thread={0}", Thread.CurrentThread.ManagedThreadId.ToString());
            Console.ReadLine();
        }

        private static void printMessage()
        {
            Console.WriteLine("Task={0}, Thread={1}",
                                    Task.CurrentId, Thread.CurrentThread.ManagedThreadId.ToString());
        }


Task<TResult> 를 보여주는 예제입니다.


실행 화면




예제 프로그램

        static void Main(string[] args)
        {
            Task<Int32> t = new Task<Int32>(n => Sum((Int32)n), 1000);
            t.Start();
            t.Wait();

            // Get the result (the Result property internally calls Wait) 
            Console.WriteLine("The sum is: " + t.Result);   // An Int32 value
            Console.ReadLine();
        }

        private static Int32 Sum(Int32 n)
        {
            Int32 sum = 0;
            for (; n > 0; n--)
                checked { sum += n; }
            return sum;
        }

posted by 따시쿵
prev 1 next