12.4 Thread에 사용되는 Delegate의 구현
스레드에서 Delegate의 사용은 기본입니다. 스레드에서는 Thread 클래스의 객체를 생성하기 위해서 Delegate인 ThreadStart를 사용합니다. 다음은 ThreadTest의 특정 메서드를 ThreadStart 델리게이트로 변환하여 Thread를 생성하는 예입니다.
ㅇ ThreadTest tt = new ThreadTest(); //임의의 객체
ㅇ Thread t = new Thread(new ThreadStart(tt.메서드));
ㅇ thread.Start();
☞ ThreadStart |
스레드를 만들기 위해서는 스레드로 사용할 메서드를 반드시 ThreadStart 델리게이트로 만들어야 합니다. ThreadStart 델리게이트는 라이브러리 내부에 선언되어 있으며 여러분은 스레드를 만들고자 할 때 ThreadStart를 사용하기만 하면 됩니다. |
위에서 보는 바와 같이 ThreadStart를 생성할 때 매개변수로 객체의 메서드를 이용합니다. 생성된 ThreadStart 객체는 Thread의 생성자 매개변수로 이용됩니다. 그리고, 생성된 스레드의 Start() 메서드를 호출하면 스레드가 동작하게 됩니다. 다음은 스레드에서 Delegate를 생성하고 Delegate를 스레드에 넣어서 실행하는 것을 보여주는 예제입니다.
& |
ThreadTest.cs |
Ü 기본적인 스레드를 테스트하는 예제 |
using System; | ||
C:\C#Example\12>csc ThreadTest.cs C:\C#Example\12>ThreadTest 스레드시작 TestThread:0 TestThread:1 TestThread:2 TestThread:3 TestThread:4 스레드종료 |
ThreadStrat 구문이 이해가 가십니까? 이미 스레드에 사용할 Delegate를 ThreadStart 형태로 만들어 두었습니다. 그리고, 이 ThreadStart 델리게이트는 Thread를 생성할 때 매개변수로 이용되는 것입니다. ThreadStart를 생성하는 부분은 Delegate의 선언이 없을 뿐 Delegate와 똑같습니다.
ThreadStart ts = new ThreadStart(tt.TestThreadMethod); //Delegate의 생성
그리고, ThreadStart 델리게이트로 스레드를 생성할 때 매개변수 형식으로 넣어 주어서 스레드를 생성합니다. 스레드가 생성되었다면 해당 스레드의 Start() 메서드만 호출해 주면 스레드는 동작하게 됩니다.
Thread t = new Thread(ts); //스레드 생성
t.Start(); //스레드 시작