david's daily developer note

C# Thread, Control.Invoke() 본문

[Develop] Language/C#

C# Thread, Control.Invoke()

mouse-david 2011. 4. 7. 15:31
728x90

1. C# 에서 (.NET Framework)
2. UI를 갖는 어플리케이션을 작성할 때 
3. 스레드를 생성해서 
4. form 의 control 객체를 접근할 때 만나게되는 에러.!

$exception  {"Control.Invoke는 별도 스레드에 만들어진 컨트롤과 상호 작용하는 데 사용해야 합니다."}
        System.Exception {System.NotSupportedException}

폼에 있는 컨트롤 박스를 별도의 스레드 (폼 도 하나의 스레드) 에서 접근하려고 하면
서로 다른 스레드가 하나의 컨트롤 객체에 접근하는 것을 방지하기 위해서 고안된 방법이라고 이해된다.
어디에서나 있는 멀티 스레드 환경에서 자원보호를 위한것이다. 

아래 코드는 myDelegate라고 하는 delegate를 선언하고,  progressbar 컨트롤을 업데이트 하는 스레드를 만든다.
myDelegate와 동일한 서명을 가지고 updateProgress 메서드를 선언하고, Invoke 메서드에게 updateProgress와 개체 배열을 파라미터로 전달한다.

private void updateProgress(int theValue, int theMax) {
    if(theMax != 0)
       proStatus.Maximum = theMax;
    proStatus.Value = theMax;
}

private delegate void myDelegate(int theValue, int theMax);

private void myThread() {
    for (int i=0 ; i < 10 ; i++) {
        this.Invoke(new myDelegate(updateProgress), new object[] {i*10,100});
        Thread.Sleep(500);
    }
}

private void cmdCreateThread_Click(object sender, System.EventArgs e) {
   new Thread(new ThreadStart(myThread)).Start();
}
728x90

'[Develop] Language > C#' 카테고리의 다른 글

C# Dictionary foreach  (0) 2011.04.08
C# ref - C# Reference  (0) 2011.04.08
C# 디렉토리 및 파일이 있는지 확인  (0) 2011.01.19
C# 쓰레드, 임계 영역 처리.  (0) 2011.01.19
C# 다수의 Process 실행하기. 경로 관리  (0) 2011.01.19