Windows Form 控制項的存取並非原本就採用安全執行緒的方式。如果您有兩個或多個執行緒管理控制項的狀態,就有可能強制控制項進入不一致的狀態。其他與執行緒有關的錯誤 也有可能如此,包括競爭情形和死結。確定存取控制項是以安全執行緒的方式來進行,是很重要的。
##CONTINUE##
對 Windows Form 控制項進行安全執行緒呼叫
若要對 Windows Form 控制項進行安全執行緒呼叫
1.查詢控制項的 InvokeRequired 屬性。
2.如果 InvokeRequired 傳回 true,就使用對控制項進行實際呼叫的委派 (Delegate) 呼叫 Invoke。
3.如果 InvokeRequired 傳回 false,便直接呼叫控制項。
private void setTextSafeBtn_Click(
object sender,
EventArgs e)
{
this.demoThread =
new Thread(new ThreadStart(this.ThreadProcSafe));
this.demoThread.Start();
}
// 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.");
}
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 });
}
else
{
this.textBox1.Text = text;
}
}
}
資料來源:
MSDN