編寫應用程序時,涉及到大量數據處理、串口通訊、Socket通訊等都會用到多線程,多線程中如何跨線程調用主界面或其餘界面下的控件是一個問題,利用invoke和delegate能夠解決。多線程
delegate其實就是函數的指針,invoke是控件的喚醒函數。函數
//跨線程設置控件comboBox的值 public delegate void commbdelegate(ComboBox cb); public void commb(ComboBox cb) { if (cb.InvokeRequired) { commbdelegate dt = new commbdelegate(commb); cb.Invoke(dt, new object[]{cb}); } else { cb.Text = "test"; } }
狀況二:函數須要返回值ui
//跨線程讀取控件ComboBox的值,並返回 public delegate string commbdelegate(ComboBox cb); public string commb(ComboBox cb) { if (cb.InvokeRequired) { commbdelegate dt = new commbdelegate(commb); IAsyncResult ia=cb.BeginInvoke(dt, new object[]{cb}); return (string)cb.EndInvoke(ia); //這裏須要利用EndInvoke來獲取返回值 } else { return cb.Text; } }