SSISO Community

갤러리정

Thread에 사용되는 Delegate의 구현 - CSharp

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;
using System.Threading;

class 
ThreadTest {
  
public void 
TestThreadMethod() {
    Console.Write(
"
스레드시작\t");
    
int i = 0
;
    
while(i < 5
) {
      Console.Write(
"TestThread:"+i+"\t"
);
      i++;
    }
    Console.Write(
"
스레드종료");
  }
//class

class 
ThreadTestMain{
  
public static void 
Main(){
    ThreadTest tt = 
new ThreadTest(); //
객체 생성
    
ThreadStart ts = new ThreadStart(tt.TestThreadMethod); //Delegate
 생성
    
Thread t = new Thread(ts); //
스레드 생성
    
t.Start(); //
스레드 시작
  
//main
//class

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(); //스레드 시작

 

결론적으로 스레드는 메서드를 하나 주면 하나의 스레드가 만들어질 있고 메서드를 Delegate 형태로 사용하는 규칙을 만들어 것입니다. 스레드를 사용하는 가장 표준적인 방법이니 잊지 마시기 바랍니다.

1254 view

4.0 stars