Thread내에서 컨트롤 속성 변경시 (Thread-safe)

by 비트겐스 posted Feb 01, 2012


Prev이전 문서

Next다음 문서


크게 작게 위로 아래로 댓글로 가기 인쇄
Extra Form

Thread 안에서 컨트롤 속성을 변경하고 싶을 때는 아래와 같이 한다.

delegate void SetTextCallback(string text);

// This event handler creates a thread that calls a 
// Windows Forms control in a thread-safe way. 
private void setTextSafeBtn_Click( 
            object sender, 
            EventArgs e)
    this.demoThread = 
    new Thread(new ThreadStart(this.ThreadProcSafe));

// This method is executed on the worker thread and makes
// a thread-safe call on the TextBox control.
private void ThreadProcSafe()
    this.SetText("This text was set safely.");

// This method demonstrates a pattern for making thread-safe
// calls on a Windows Forms control. 
// If the calling thread is different from the thread that
// created the TextBox control, this method creates a
// SetTextCallback and calls itself asynchronously using the
// Invoke method.
// If the calling thread is the same as the thread that created
// the TextBox control, the Text property is set directly.

private void SetText(string text)
    // InvokeRequired required compares the thread ID of the
    // calling thread to the thread ID of the creating thread.
    // If these threads are different, it returns true.
    if (this.textBox1.InvokeRequired)
         SetTextCallback d = new SetTextCallback(SetText);
         this.Invoke(d, new object[] { text });
         this.textBox1.Text = text;