프로그램/C# - Study / / 2010. 10. 13. 15:18

C# - Ex26Thread 쓰래드

반응형

윈폼 부분
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Ex26Thread
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //1. Synchronized Method Call
        private void button1_Click(object sender, EventArgs e)
        {
            Console.WriteLine("1. Before Calling DoWork");
            TheWorker worker = new TheWorker();

            worker.DoWork();

            Console.WriteLine("4. After Calling DoWork");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Console.WriteLine("1. Before Calling DoWork");
            TheWorker worker = new TheWorker();

                                             // 메소드 자리
            ThreadStart ts = new ThreadStart(worker.DoWork); // 델리게이트  생성
            Thread thread = new Thread(ts); // 쓰레드 생성
            thread.IsBackground = true; // 프로그램 종료하면 쓰레드를 즉시 종료

            Console.WriteLine("Thread State : " + thread.ThreadState);
            thread.Start(); // 쓰레드 실행 요청

            Thread.Sleep(1000);
            Console.WriteLine("Thread State : " + thread.ThreadState);

            Console.WriteLine("4. After Calling DoWork");
        }

        //using Thread Pool
        private void button3_Click(object sender, EventArgs e)
        {
            Console.WriteLine("1. Before Calling DoWork");
            TheWorker worker = new TheWorker();

            WaitCallback callback = new WaitCallback(worker.DoWork2);

            //내부적 쓰레드(암시적)
            ThreadPool.QueueUserWorkItem(callback);

            Console.WriteLine("4. After Calling DoWork");
        }

        //Asunchronous Pattern
        private void button4_Click(object sender, EventArgs e)
        {
            TheWorker worker = new TheWorker();
            MethodInvoker invoker = new MethodInvoker(worker.DoWork);

            //worker.DoWork();  // worker.DoWork 호출 직접 호출    동기방식
            //invoker.Invoke(); // worker.DoWork 호출 델리게이트를 통해 호출    동기방식
            //Thread thread = new Thread(worker.DoWork);
            //thead.Start(); 쓰레드를 통해 호출         비동기 방식

            Console.WriteLine("1. Before Calling DoWork");
            //invoker.Invoke(); // 동기방식호출

            AsyncCallback callback = new AsyncCallback(MyCallback);
            invoker.BeginInvoke(callback, invoker); // 비동기 방식 호출( 메서드가 종료된 후 EndInvoke 호출을 해야 합니다.)

            Console.WriteLine("4. Before Calling DoWork");

        }

        private void MyCallback(IAsyncResult result)
        {
            MethodInvoker invoker = (MethodInvoker)result.AsyncState;
            invoker.EndInvoke(result);
            Console.WriteLine("After Completing Thread Method");
        }

        private void button5_Click(object sender, EventArgs e)
        {
            TheWorker worker1 = new TheWorker();
            TheWorker worker2 = new TheWorker();

            Thread thread1 = new Thread(new ThreadStart(worker1.DoSum));
            Thread thread2 = new Thread(worker2.DoSum);

            thread1.Start();
            thread2.Start();
        }
    }
}

--------------------------------------------------------------------------------------------------------------
클래스 추가

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Ex26Thread
{
    class TheWorker
    {
        public void DoWork()
        {
            Console.WriteLine("2. Beginning of DoWork");
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(1000);  //1초간 실행 중지
            }
            Console.WriteLine("3. End of DoWork");
        }

        public void DoWork2(object state)
        {
            Console.WriteLine("2. Beginning of DoWork2");
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(1000); //1초간 실행 중지
            }
            Console.WriteLine("3. End of DoWork2");
        }

        private static int sum;
        private static object key = new object();
        public void DoSum()
        {
            //lock(key)
            //{
            //    sum = 0;
            //    for (int i = 1; i <= 1000; i++)
            //    {
            //        sum = sum + i;
            //        if (i % 100 == 0 && i != 1000)
            //            Thread.Sleep(1000);
            //    }
            //    Console.WriteLine(
            //        "RESULT IN THREAD {0} : {1}",
            //        Thread.CurrentThread.ManagedThreadId,
            //        sum);
            //}

            //Monitor.Enter(key);
            //{
            //    sum = 0;
            //    for (int i = 1; i <= 1000; i++)
            //    {
            //        sum = sum + i;
            //        if (i % 100 == 0 && i != 1000)
            //            Thread.Sleep(1000);
            //    }
            //    Console.WriteLine(
            //        "RESULT IN THREAD {0} : {1}",
            //        Thread.CurrentThread.ManagedThreadId,
            //        sum);
            //}
            //Monitor.Exit(key);

            //mre.WaitOne();//신호 상태 대기
            //mre.Reset();//비신호 상태로 변경
            //{
            //    sum = 0;
            //    for (int i = 1; i <= 1000; i++)
            //    {
            //        sum = sum + i;
            //        if (i % 100 == 0 && i != 1000)
            //            Thread.Sleep(1000);
            //    }
            //    Console.WriteLine(
            //        "RESULT IN THREAD {0} : {1}",
            //        Thread.CurrentThread.ManagedThreadId,
            //        sum);
            //}
            //mre.Set();//신호 상태로 변경

            are.WaitOne(); //신호 상태 대기
            //are.Reset();//비신호 상태로 변경

            {
                sum = 0;
                for (int i = 1; i <= 1000; i++)
                {
                    sum = sum + i;
                    if (i % 100 == 0 && i != 1000)
                        Thread.Sleep(1000);
                }
                Console.WriteLine(
                    "RESULT IN THREAD {0} : {1}",
                    Thread.CurrentThread.ManagedThreadId,
                    sum);
            }
            are.Set(); //신호 상태로 변경
        }

        private static ManualResetEvent mre =
            new ManualResetEvent(true);
        private static AutoResetEvent are =
            new AutoResetEvent(true);
    }
}


반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유