본문 바로가기

Programing/C#

c# 크로스 스레드(CheckForIllegalCrossThreadCalls)

 

 

// This event handler creates a thread that calls a
// Windows Forms control in an unsafe way.
private void setTextUnsafeBtn_Click(
object sender,
EventArgs e)
{
this.demoThread =
new Thread(new ThreadStart(this.ThreadProcUnsafe));

this.demoThread.Start();
}

// This method is executed on the worker thread and makes
// an unsafe call on the TextBox control.
private void ThreadProcUnsafe()
{
this.textBox1.Text = "This text was set unsafely.";
}

위 소스는 msdn에서 퍼왔습니다.

보시면 버튼을 클릭하면 demoThread를 하나 만들어서

해당 스레드가 ThreadProcUnsafe() 함수를 돌리는 모양인데

ThreadProcUnsafe함수 안에서는 textBox1 을 건드리고 있습니다.

하지만 메인 Thread가 메인 UI를 관리 함으로 이 호출은

demoThread가 메인 trhead를 침범하기 때문에 안전하지 않는 방법이라고 설명을 하고 있습니다.

C#에서는 이 문제를 해결하기 위해 invoke와 delegate를 사용해서 우회한다고 합니다. android에서는 헨들러를 이용해서 메인 ui를 만졌던 기억이 있는데 이와 비슷하다고 생각 됩니다.

만약 위 문제를 신경안쓰고 Thread를 사용하고 싶다면

저기 demoTrhead 에 CheckForIllegalCrossThreadCalls = false;

라고 선언해 주면 thread가 충돌해도 관여하지않고 돌아가게 됩니다.

하지만 이방법은 추천하는 방법들은 아니더군요~

만약 위 CheckForIllegalCrossThreadCalls = false;르 사용 할려면

 

private void ThreadProcUnsafe()
{

CheckForIllegalCrossThreadCalls = false;
this.textBox1.Text = "This text was set unsafely.";
}

 

이런식으로 사용해주면 됩니다.

'Programing > C#' 카테고리의 다른 글

c# 크로스 스레드, 델리게이트 delegate 활용  (0) 2015.01.05
(C#) Semaphore Release  (0) 2014.07.08
(C#) FiFo Semaphore  (0) 2014.07.02