直接在背景執行緒設定控制項屬性:
private void ThreadFunction() {
while (true) {
this.textBox1.Text = DateTime.Now.ToString();
Thread.Sleep(1000);
}
}
拋出異常:Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on. .NET 2.0+ 強化安全機制,禁止跨執行緒直接存取控制項。
private void Form1_Load(object sender, EventArgs e) {
Control.CheckForIllegalCrossThreadCalls = false; // 全域關閉檢查
Thread thread = new Thread(ThreadFunction);
thread.IsBackground = true; thread.Start();
}
程式可跑,但 CheckForIllegalCrossThreadCalls 為 static,修改影響全域。專案其他人員若改回 true,本模組即失效。且跨執行緒存取本應檢查,關閉檢查屬治標不治本。