發布時間:2020-08-06 12:21 作者:獨孤劍 閱讀:1287
Winform 多線程中處理UI控件, 多線程中不能直接操作UI控件, 會引發線程安全異常
using System; using System.Threading; using System.Windows.Forms; namespace WindowsFormsApp10 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /* 在窗體拖拽2個button,1個label */ private void button1_Click(object sender, EventArgs e) { Thread thread = new Thread(Test1); thread.Start(); } // 線程中直接操作控件會引發線程安全異常 // Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.' private void Test1() { for (int i = 0; i < 1000; ++i) { label1.Text = i.ToString(); } } // Control.CheckForIllegalCrossThreadCalls = false;// 可以解決掉所有控件安全異常 private void Test2() { Control.CheckForIllegalCrossThreadCalls = false; for (int i = 0; i < 1000; ++i) { label1.Text = i.ToString(); } } // 在線程中用委托操作UI控件 delegate void InvokeHandler(); private void Test3() { for (int i = 0; i < 1000; ++i) { // net 2.0 this.Invoke(new InvokeHandler(delegate () { label1.Text = i.ToString(); })); } } // 在線程中用委托操作UI控件 private void Test4() { for (int i = 0; i < 1000; ++i) { // net 3.5 以上 this.Invoke((Action)(() => { label1.Text = i.ToString(); })); } } } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞