본문 바로가기
C#/책 예제

C# Task Task 클래스 사용하기.

by HyunS_ 2019. 6. 8.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace ThreadNTask
{
    class Program
    {
        static void Main(string[] args)
        {
            string srcFile = args[0];

            Action<object> fileCopyAction = (object state) =>
            { 
                string[] paths = (string[])state;
                File.Copy(paths[0], paths[1]);

                Console.WriteLine("TaskID: {0}, ThreadID: {1}, {2} was copied to {3}", Task.CurrentId, Thread.CurrentThread.ManagedThreadId, paths[0], paths[1]);
            };

            Task task1 = new Task(fileCopyAction, new string[]{srcFile, srcFile + ".copy1"});
            Task task2 = Task.Run(() => 
            { 
                fileCopyAction(new string[] { srcFile, srcFile + ".copy2"});
            });

            task1.Start();

            Task task3 = new Task(fileCopyAction, new string[]{srcFile, srcFile + ".copy3"});

            task3.RunSynchronously();

            task1.Wait();
            task2.Wait();
            task3.Wait();
        }
    }
}
728x90

댓글