노주현 개인 블로그

Thread 관련 내용 총정리 본문

프로그래밍/C#

Thread 관련 내용 총정리

해인아빠408 2022. 1. 5. 23:24

동기 

1. 상대방의 일정 신호(결과 신호)에 의해서 다음 동작으로 이뤄짐

2. 어떤 루틴을 완전히 끝내고 제어를 반납

 

비동기

1. 상대방의 상태와 관계없이 일방적으로 동작하면 비동기

2. 동작이 안 끝났어도 일단 제어권을 반납한 후 작업 계속

 

 

BeginInvoke / EndInvoke 

int threadID; // 비 동기 실행에서 Thread 를 구분하는 ID

// delegate 인스턴스 생성
AasyncDelegateCaller caller = new AasyncDelegateCaller(AasyncDelegate);

// 비동기 시작
IAsyncResult result = caller.BeginInvoke(3000, out threadID, null, null);

// EndInvoke 를 통해서 비동기 실행이 완료될 때까지 대기 함.
string returnValue = caller.EndInvoke(out threadID, result);


public string AasynDelegate(int delay, out int threadID)
{
	Thread.Sleep(delay);
    threadID = Thread.CurrentThread.ManagedThreadID;
}

1. BeginInvoke 로 실행하면 메인 스레드와 별개의 다른 스레드에서 실행

2. 그냥 Invoke 로 실행하면 기존과 같이 동기적으로 실행 (Thread 효과 없음)

3. BeginInvoke 로 실행하면 언제나 EndInvoke 가 필요

4. 이 방식은 결과적으로 메인 스레드에서 EndInvoke 가 실행될 때까지 대기하기 때문에 비동기로서의 이점이 없다.

 

 

int threadID; // 비 동기 실행에서 Thread 를 구분하는 ID

// delegate 인스턴스 생성
AasyncDelegateCaller caller = new AasyncDelegateCaller(AasyncDelegate2);

// 비동기 시작
IAsyncResult result = caller.BeginInvoke(3000, out threadID, new AsyncCallback(AsyncDelegateCallback), caller);

// EndInvoke 를 통해서 비동기 실행이 완료될 때까지 대기 함.
string returnValue = caller.EndInvoke(out threadID, result);


// 
public string AasynDelegate2(int delay, out int threadID)
{
	Thread.Sleep(delay);
    threadID = Thread.CurrentThread.ManagedThreadID;
}


public void AsyncDelegateCallback(IAsyncResult result)
{
	AasyncDelegateCaller caller = (AasyncDelegateCaller)result.AsyncState;
    
    int threadID:
    
    string returnValue = caller.EndInvoke(out threadID, result);    
}

1. 메인 스레드에서 EndInvoke 가 실행되지 않고, AsyncDelegateCallback 메서드에서 실행이 되도록 변경

2. 이 때 비동기 실행이 언제 종료되는지 상관 없이 메인 스레드에서 별도의 작업을 계속 진행

 

 

 

 

Thread 실행과 Cross Thread 해결 방안 

Thread thread = new Thread(new ThreadStart(delegate()
{
    // ThreadStart 델리게이트를 통해 해당 Thread 가 실행할 작업 내용을 선언
    if(this.InvokeRequired)
    {
    	this.Invoke(new Action(delegate()
        {
        	//Form 의 컨트롤을 다루는 code  
        }));
    }
}));

thread.Start();

'프로그래밍 > C#' 카테고리의 다른 글

문자열 인코딩  (0) 2022.01.21
클래스 상속 - Interface  (0) 2022.01.18
Momory Copy 여러가지 방식  (0) 2022.01.03
Bitmap & Byte[]  (0) 2022.01.03
Process 실행 여부 확인  (0) 2021.12.30
Comments