using System;
using System.IO;
using System.Threading.Tasks;

namespace ThreadNTask
{
    class Program
    {
        static void Main(string[] args)
        {
           if(args.Length < 2)
           {
                Console.WriteLine("Usage: AsyncFileIO <Source> <Destination>");
                return;
           }

           DoCopy(args[0], args[1]);

           Console.ReadLine();
        }

        static async Task<long> CopyAsync(string fromPath, string toPath)
        {
            using(var fromStream = new FileStream(fromPath, FileMode.Open))
            {
                long totalCopied = 0;

                using(var toStream = new FileStream(toPath, FileMode.Create))
                {
                    byte[] buffer = new byte[1024];
                    int nRead = 0;
                    while((nRead = await fromStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                    {
                        await toStream.WriteAsync(buffer, 0, nRead);
                        totalCopied += nRead;
                    }
                }

                return totalCopied;
            }
        }

        static async void DoCopy(string fromPath, string toPath)
        {
            long totalCopied = await CopyAsync(fromPath, toPath);
            Console.WriteLine($"Copied total {totalCopied} Bytes");
        }
    }
}
using System;
using System.Threading.Tasks;

namespace ThreadNTask
{
    class Program
    {
        static void Main(string[] args)
        {
            Caller();

            Console.ReadLine();
        }

        async static private void MyMethodAsync(int count)
        {
            Console.WriteLine("C");
            Console.WriteLine("D");

            await Task.Run(async() =>
            {
                for(int i = 1; i < count; i++)
                {
                    Console.WriteLine($"{i}/{count}.");
                    await Task.Delay(1000);
                }
            });

            Console.WriteLine("G");
            Console.WriteLine("H");
        }

        static void Caller()
        {
            Console.WriteLine("A");
            Console.WriteLine("B");

            MyMethodAsync(3);

            Console.WriteLine("E");
            Console.WriteLine("F");


        }
    }
}
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ThreadNTask
{
    class Program
    {
        static void Main(string[] args)
        {
            long from = Convert.ToInt64(args[0]);
            long to   = Convert.ToInt64(args[1]);

            Console.WriteLine("Please press enter to start");
            Console.ReadLine();
            Console.WriteLine("Started");

            DateTime startTime = DateTime.Now;
            List<long> total = new List<long>();

            Parallel.For(from, to, (long i) => 
            {
                if(IsPrime(i))
                { 
                    total.Add(i);
                }
            });

            DateTime endTime = DateTime.Now;

            TimeSpan ellapsed = endTime - startTime;

            Console.WriteLine("Prime number count between {0} and {1}: {2}", from, to, total.Count);
            Console.WriteLine("Ellapsed time : {0}", ellapsed);
            
        }

        static bool IsPrime(long number)
        { 
            if(number < 2)
            { 
                return false;
            }

            if(number % 2 == 0 && number != 2)
            { 
                return false;
            }

            for (long i = 2; i < number; i++)
            {
                if(number % i == 0)
                { 
                    return false;
                }
            }

            return true;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ThreadNTask
{
    class Program
    {
        static void Main(string[] args)
        {
            long from = Convert.ToInt64(args[0]);
            long to   = Convert.ToInt64(args[1]);

            int taskCount = Convert.ToInt32(args[2]);

            Func<object, List<long>> FindPrintFunc = (objRange) =>
            { 
                long[] range = (long[])objRange;
                List<long> found = new List<long>();

                for(long i = range[0]; i < range[1]; i++)
                {
                    if(IsPrime(i))
                    { 
                        found.Add(i);
                    }
                }

                return found;
            };

            Task<List<long>>[] tasks = new Task<List<long>>[taskCount];

            long currentFrom = from;
            long currentTo   = to / tasks.Length;

            for(int i = 0; i < tasks.Length; i++)w
            {
                Console.WriteLine("Tasks[{0}] : {1} ~ {2}", i ,currentFrom, currentTo);
                tasks[i] = new Task<List<long>>(FindPrintFunc, new long[]{currentFrom, currentTo});
                currentFrom = currentTo + 1;

                if(i == tasks.Length - 2)
                {
                    currentTo = to;

                }
                else
                { 
                    currentTo = currentTo + (to / tasks.Length);
                }
            }

            Console.WriteLine("Please press enter to start");
            Console.ReadLine();
            Console.WriteLine("Started");

            DateTime startTime = DateTime.Now;

            foreach(Task<List<long>> task in tasks)
            {
                task.Start();
            }

            List<long> total = new List<long>();

            foreach (Task<List<long>> task in tasks)
            {
                task.Wait();
                total.AddRange(task.Result.ToArray());
            }

            DateTime endTime = DateTime.Now;

            TimeSpan ellapsed = endTime-  startTime;

            Console.WriteLine("Prime number between {0} and {1}", from, to, total.Count);

            Console.WriteLine("Ellapsed time: {0}", ellapsed);
        }

        static bool IsPrime(long number)
        { 
            if(number < 2)
            { 
                return false;
            }

            if(number % 2 == 0 && number != 2)
            { 
                return false;
            }

            for (long i = 2; i < number; i++)
            {
                if(number % i == 0)
                { 
                    return false;
                }
            }

            return true;
        }
    }
}
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();
        }
    }
}
using System;
using System.Threading;

namespace ThreadNTask
{
    class Program
    {
        static void Main(string[] args)
        {
            Counter counter = new Counter();

            Thread increaseThread = new Thread(new ThreadStart(counter.Increase));
            Thread decreaseThread = new Thread(new ThreadStart(counter.Decrease));

            increaseThread.Start();
            decreaseThread.Start();

            increaseThread.Join();
            decreaseThread.Join();

            Console.WriteLine(counter.Count);

        }
    }

    class Counter
    { 
        const int LOOP_COUNT = 1000;

        readonly object thisLock;
        bool lockedCount = false;

        private int count;
        
        public int Count
        { 
            get{ return count; }
        }

        public Counter()
        { 
            thisLock = new object();
            count = 0;
        }

        public void Increase()
        { 
            int loopCount = LOOP_COUNT;
            while(loopCount-- > 0)
            {
                lock(thisLock)
                {
                    while(count < 0 || lockedCount == true)
                    {
                        Monitor.Wait(thisLock);
                        lockedCount = true;
                        count ++;
                        lockedCount = false;

                        Monitor.Pulse(thisLock);
                    }
                }
            }
        }

        public void Decrease()
        { 
            int loopCount = LOOP_COUNT;

            while (loopCount-- > 0)
            {
                lock (thisLock)
                {
                    while (count < 0 || lockedCount == true)
                    {
                        Monitor.Wait(thisLock);
                        lockedCount = true;
                        count++;
                        lockedCount = false;

                        Monitor.Pulse(thisLock);
                    }
                }
            }
        }
    }
}
using System;
using System.Threading;

namespace ThreadNTask
{
    class Program
    {
        static void Main(string[] args)
        {
            Counter counter = new Counter();

            Thread increaseThread = new Thread(new ThreadStart(counter.Increase));
            Thread decreaseThread = new Thread(new ThreadStart(counter.Decrease));

            increaseThread.Start();
            decreaseThread.Start();

            increaseThread.Join();
            decreaseThread.Join();

            Console.WriteLine(counter.Count);

        }
    }

    class Counter
    { 
        const int LOOP_COUNT = 1000;

        readonly object thisLock;

        private int count;
        
        public int Count
        { 
            get{ return count; }
        }

        public Counter()
        { 
            thisLock = new object();
            count = 0;
        }

        public void Increase()
        { 
            int loopCount = LOOP_COUNT;
            while(loopCount-- > 0)
            {
                Monitor.Enter(thisLock);
                try
                {
                    count++;
                }
                finally
                { 
                    Monitor.Exit(thisLock);
                }
                Thread.Sleep(1);
            }
        }

        public void Decrease()
        { 
            int loopCount = LOOP_COUNT;

            while (loopCount-- > 0)
            {
                Monitor.Enter(thisLock);
                try
                {
                    count--;
                }
                finally
                {
                    Monitor.Exit(thisLock);
                }
                Thread.Sleep(1);
            }
        }
    }
}
using System;
using System.Threading;

namespace ThreadNTask
{
    class Program
    {
        static void Main(string[] args)
        {
            Counter counter = new Counter();

            Thread increaseThread = new Thread(new ThreadStart(counter.Increase));
            Thread decreaseThread = new Thread(new ThreadStart(counter.Decrease));

            increaseThread.Start();
            decreaseThread.Start();

            increaseThread.Join();
            decreaseThread.Join();

            Console.WriteLine(counter.Count);

        }
    }

    class Counter
    { 
        const int LOOP_COUNT = 1000;

        readonly object thisLock;

        private int count;
        
        public int Count
        { 
            get{ return count; }
        }

        public Counter()
        { 
            thisLock = new object();
            count = 0;
        }

        public void Increase()
        { 
            int loopCount = LOOP_COUNT;
            while(loopCount-- > 0)
            {
                lock(thisLock)
                { 
                    count++;
                }
                Thread.Sleep(1);
            }
        }

        public void Decrease()
        { 
            int loopCount = LOOP_COUNT;

            while(loopCount-- > 0)
            {
                lock(thisLock)
                { 
                    count--;
                }
                Thread.Sleep(1);
            }
        }
    }
}
using System;
using System.Threading;

namespace ThreadNTask
{
    class Program
    {
        static void Main(string[] args)
        {
            SlideTask slideTask = new SlideTask(100);

            Thread thread = new Thread(new ThreadStart(slideTask.KeepAlive));
            thread.IsBackground = true;

            Console.WriteLine("스레드 시작");
            thread.Start();

            Thread.Sleep(100);

            Console.WriteLine("스레드 종료");
            thread.Interrupt();

            Console.WriteLine("스레드가 멈출때까지 대기");
            thread.Join();

            Console.WriteLine("종료");
        }
    }

    class SlideTask
    { 
        private int count;

        public SlideTask(int count)
        { 
            this.count = count;
        }

        public void KeepAlive()
        {
            try
            {
                Console.WriteLine("실행중인 스레드가 중단되지 않습니다.");
                Thread.SpinWait(100000000);

                while(count > 0)
                {
                    Console.WriteLine($"{count --} left");

                    Console.WriteLine("WaitJoinSleep State 로 바뀌는 중");
                    Thread.Sleep(10);
                }
                Console.WriteLine("Count: 0");
            }
            catch(ThreadAbortException threadAbortException)
            {
                Console.WriteLine(threadAbortException);
            }
            finally
            {
                Console.WriteLine("리소스 지우기");
            }
        }

            

    }

    
}

'C# > 책 예제' 카테고리의 다른 글

C# Thread Monitor 키워드를 이용한 동기화  (0) 2019.06.08
C# Thread lock 키워드를 이용한 동기화  (0) 2019.06.08
C# Thread 인터럽트로 종료하기.  (0) 2019.06.08
C# Thread 상태 변화  (0) 2019.06.08
C# Thread 임의 종료  (0) 2019.06.08
C# / Thread 시작  (0) 2019.06.08
using System;
using System.Threading;

namespace ThreadNTask
{
    class Program
    {
        static void Main(string[] args)
        {
            PrintThreadState(ThreadState.Running);

            PrintThreadState(ThreadState.StopRequested);

            PrintThreadState(ThreadState.SuspendRequested);

            PrintThreadState(ThreadState.Background);

            PrintThreadState(ThreadState.Unstarted);

            PrintThreadState(ThreadState.Stopped);

            PrintThreadState(ThreadState.WaitSleepJoin);

            PrintThreadState(ThreadState.Suspended);

            PrintThreadState(ThreadState.AbortRequested);

            PrintThreadState(ThreadState.Aborted);

            PrintThreadState(ThreadState.Aborted | ThreadState.Stopped);
        }

        private static void PrintThreadState(ThreadState threadState)
        {
            Console.WriteLine("{0, -16} : {1}", threadState, (int)threadState);
        }
    }
}

'C# > 책 예제' 카테고리의 다른 글

C# Thread Monitor 키워드를 이용한 동기화  (0) 2019.06.08
C# Thread lock 키워드를 이용한 동기화  (0) 2019.06.08
C# Thread 인터럽트로 종료하기.  (0) 2019.06.08
C# Thread 상태 변화  (0) 2019.06.08
C# Thread 임의 종료  (0) 2019.06.08
C# / Thread 시작  (0) 2019.06.08

+ Recent posts